It seems that shared_ptr hides the lack of a virtual destructor in the base class.
For this code:
class IInt { public: ~IInt() {}
shared_ptr - no virtual destructor needed
At the end of this block - shared_ptr<IInt> correctly destroys c101 - quite surprisingly, the absence of a 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 - required virtual destructor
{ 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; }
The way out is the lack of proper destruction :
103
104
Question:
I do not ask to explain how this happens, it works just like that. I hope I understand correctly that the whole point is the differences in destruction in shared_ptr and unique_ptr .
shared_ptr destroys the object attached to its control unit, and this object, when it was created, still exists.unique_ptr - the killing object is attached to each unique pointer, and its statically linked - and not a change - cannot be taken from another pointer.
I rather ask:
- Is this documented somewhere? Is this a difference in behavior? Any note in the C ++ standard says this can be confusing.
- Are there any plans to change it?
Of course, please correct and / or fill out my short explanation, if necessary.
source share