Role of the destructors while using smart pointers as member variable
Jun 4, 2015 at 12:03pm UTC
Hello forum,
I assume the fact the we do not have release any resource anymore explicitly as long we adopt the standard C++11. Lets check the following snippet:
1 2 3 4 5 6 7 8 9 10 11 12
class B;
class A
{
public :
A();
~A();
private :
shared_ptr<B> mSharedBvar;
std::vector<shared_ptr<C>> mSharedCVector;
}
Inside the constructor we may allocate memory and container for memory as follows:
1 2 3 4 5 6 7
...............
mSharedBvar = new B();
for (unsigned int i = 0; i < 10; ++i)
{
mSharedCVector.push_back(new C());
}
Inside the destructor we only need to clear the vector, right ?
Do I have to take care of anything else?
Thanks
Jun 4, 2015 at 3:05pm UTC
Inside the constructor we may allocate memory and container for memory as follows:
Yes.
While shared_ptr<T> has an explicit constructor that takes a pointer of type T, I prefer to explicitly pass a shared_ptr.
mSharedCVector.push_back(shared_ptr<C>(new C));
While unnecessary, it makes clear that a shared_ptr is being pushed. I'm sure others may disagree.
Inside the destructor we only need to clear the vector, right ?
The clear is not necessary. vector's destructor destroys all container elements.
Jun 4, 2015 at 3:47pm UTC
Jun 4, 2015 at 6:57pm UTC
This is also assuming that you really want the shared_ptr semantics:
1 2 3
A a1;
A a2(a1);
// a1 and a2 now share the B and C objects
If you don't want to share the objects, then there's probably no reason to use pointers at all, just embed the objects directly.
Jun 8, 2015 at 12:51pm UTC
Thanks for all the feedback,
I have noticed one issue. I have declared a shared pointer as member variable as follows:
1 2 3 4 5 6 7 8 9 10 11
class A{};
class B
{
public :
B();
std::shared_ptr<A> mAPekare;
};
I get error if I write the following:
1 2 3 4
B::B()
{
mAPekare = new A();
}
The code compiles if I code the following instead:
mAPekare = std::make_shared<A>();
I did not find any where in any reference that the former way of allocating memory is wrong. Any idea?
I know that the latter way is the most recommended, but the former should not be wrong either.
Thanks
Jun 8, 2015 at 2:38pm UTC
The constructor is explicit.
This would compile: mAPekare = std::shared_ptr<A>( new A() ) ;
Topic archived. No new replies allowed.