Why is the output of the following code different depending on whether I use a shared_ptr
or unique_ptr
? The output of shared_ptr
makes sense, because the object is fully destructed, while in the case of unique_ptr
, only the base class part is destructed. I thought that when I use a smart pointer, I don't have to make the destructor virtual
for the full object to be destructed successfully.
#include <iostream>
#include <memory>
using namespace std;
class base
{
public:
base(){cout <<"base class constructor " <<endl;}
~base(){ cout <<"base class Destructor "<<endl;}
};
class derv: public base
{
public:
derv(){cout <<"derv class constructor " <<endl;}
~derv(){ cout <<"derv class Destructor "<<endl;}
};
When the above code is called by shared_ptr
, the full object (base
and derv
) is destructed.
int main()
{
shared_ptr<base> p1 (new derv);
}
Output:
base class constructor
derv class constructor
derv class Destructor
base class Destructor
When called by unique_ptr
, only the base
part is destructed but not the derv
part.
int main()
{
unique_ptr<base> p1 (new derv);
}
Output:
base class constructor
derv class constructor
base class destructor