Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why shared_ptr can access with ingoring the "protected access right"

Tags:

c++

shared-ptr

I made some testing with shared_ptr,and i can't think out the matter below.I just started to learn the boost library. Is there anybody can tell me the reason?

#include <boost\shared_ptr.hpp>
#include <iostream>

class A 
{
public:  
    virtual void sing()
    {
        std::cout<<"A";
    }
protected:  virtual ~A() {};

};

class B : public A 
{
public:  
    virtual void sing() 
    {   
        std::cout << "B"; 
    }
    virtual ~B() {};
};


int foo()
{   
    boost::shared_ptr<A> pa(new B());
    pa->sing();

    delete static_cast<B*>(pa.get());

    delete pa.get(); //this line has a problem error C2248: “A::~A”: can't access protected memmber(declared in class“A")   
    return 0;
}

int main()
{
    foo();
    return 0;
}

but it can be compiled when that line is commented out. Surely it doesn't mean that the shared_ptr will delete the pointer internally maintained out of the main function, just like what i did. Is there any difference between the pointer returned by pa.get() and the pointer internally maintained?

like image 384
liximomo Avatar asked May 01 '12 11:05

liximomo


1 Answers

I believe that delete is called during destruction of the shared_ptr on the type of the pointer passed into the constructor. Have a look at the constructor here:

http://www.boost.org/doc/libs/1_49_0/libs/smart_ptr/shared_ptr.htm#constructors

So when your pa goes out of scope, B::~B( ) is called rather than the destructor of the type contained - A::~A ( which would be impossible because it's declared protected).

like image 74
Nick Avatar answered Sep 23 '22 06:09

Nick