Looks like shared_ptr hides the lack of virtual destructor in base class.
For this code:
class IInt {
public:
/*virtual*/ ~IInt() {} // Lack of virtual destructor!
virtual int get() const = 0;
};
class Int : public IInt {
public:
Int(int a) : a(a) {}
~Int() { cout << "~Int:" << a << endl; }
int get() const override { return a; }
private:
int a;
};
shared_ptr - virtual destructor not needed
At the end of this block - shared_ptr<IInt>
properly destructs the c101 - quite surprisingly the lack of virtual destructor in IInt
is not a problem here:
{
std::shared_ptr<IInt> c101 = std::make_shared<Int>(101);
std::shared_ptr<IInt> c102(new Int(102));
cout << c101->get() << endl;
cout << c102->get() << endl;
}
Output:
101
102
~Int:102
~Int:101
unique_ptr - virtual destructor needed
{
std::unique_ptr<IInt> c103 = std::make_unique<Int>(103);
std::unique_ptr<IInt> c104(new Int(104));
cout << c103->get() << endl;
cout << c104->get() << endl;
}
Output - lack of proper destruction:
103
104
Question:
I am not asking for explanation how it happens it works that way.
I hope I properly understand that all is the matter of destruction differences in shared_ptr
and unique_ptr
.
shared_ptr
has destroying object attached to its control block - and this object once created is still there.unique_ptr
- destroying object is attached to every single unique pointer and its statically linked - and not change - cannot be taken from other pointer.
I am rather asking:
- Is that somewhere documented? This difference in behavior? Any note in C++ standard saying that this can be confusing.
- Are there any plans to change it?
Of course please correct and/or complete my short explanation if that is needed.