Looks like make_shared 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;
};
make_shared - 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);
cout << c101->get() << endl;
}
Output:
101
~Int:101
shared_ptr initialized with new expression - virtual destructor needed
{
std::shared_ptr<IInt> c102(new Int(102));
cout << c102->get() << endl;
}
Output - lack of proper destruction:
102
unique_ptr - virtual destructor always 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_ptrhas destroying object attached to its control block - and this object once created inmake_sharedis 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: 1. Is that somewhere documented? This difference in behavior? Any note in C++ standard saying that this can be confusing. 1. Are there any plans to change it?
Of course please correct and/or complete my short explanation if that is needed.
Aucun commentaire:
Enregistrer un commentaire