Role of the destructors while using smart pointers as member variable

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 ?

 
mSharedCVector.clear();


Do I have to take care of anything else?


Thanks
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.






> Inside the constructor we may allocate memory and container for memory as follows:

Strongly favour std::make_shared<T>( args... ) over an explicit new T( args... )
http://en.cppreference.com/w/cpp/memory/shared_ptr/make_shared


> Inside the destructor ...

Consider not declaring a destructor at all.
Rule of zero: http://en.cppreference.com/w/cpp/language/rule_of_three
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.
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
The constructor is explicit.

This would compile: mAPekare = std::shared_ptr<A>( new A() ) ;
Topic archived. No new replies allowed.