A safty issue regarding shared_ptr

Hi everyone, I have a base class A and a derived class B:

1
2
3
4
5
class A
{...};

class B : public A
{...};


Now, in one part of my program, I need to operate on type B, so I use shared_ptr<B> to hold all the data. But later, these data will be processed through its base type A. So I use shared_ptr<A> to share the ownership of the same data:

1
2
3
shared_ptr<B> spB(new B());
...
shared_ptr<A> spA(spB);


It looks fine to me, but I'm not sure if it is completely safe. Would there be any potential risk that I should be aware of?

Many thanks,
MiMiChaCha
If destructor of A is virtual, you shouldn't have problems.
> Would there be any potential risk that I should be aware of?

The destructor of the base class should be virtual; but even without it, the posted code is safe.

Prefer using std::make_shared() over new
http://en.cppreference.com/w/cpp/memory/shared_ptr/make_shared

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <memory>

struct base {};

struct derived : base { ~derived() { std::cout << "derived::~derived\n" ; } };

int main()
{
    {
        std::shared_ptr<base> p1( new derived ) ;
        std::shared_ptr<derived> p2( new derived ) ;
        std::shared_ptr<base> p3 = p2 ;
        std::shared_ptr<base> p4 = std::make_shared<derived>() ;
    }
    std::cout << "the three derived class objects should have been destroyed by now\n" ;

    {
        std::cout << "without a virtual destructor for base, there is trouble here\n" ;
        std::shared_ptr<base> p( static_cast<base*>( new derived ) ) ;
    }
    std::cout << "the wrong destructor would have been called for the derived class object\n" ;
}

http://ideone.com/LPsD36
Thank you, MiiNiPaa and JLBorges!
Prefer using std::make_shared() over new


I didn't even know this existed. Many thanks.
Topic archived. No new replies allowed.