Different destruction depending on how shared_ptr is created

Hi,
I have the following:

struct Widget {
~Widget() {
cout << "~Widget: " << this << endl;
}
void operator delete(void*p) {
cout << "operator delete: " << p << endl;
::operator delete(p);
}
};

Then I create shared ptrs:

auto msw = std::make_shared<Widget>(21, 45.78);

auto sw = std::shared_ptr<Widget>(new Widget{ 23, 55.8} );

Which I null out with:

msw = nullptr;
sw = nullptr;

And I get the following output:

~Widget: 0x102a00018
~Widget: 0x1028000e0
Widget::operator delete 0x1028000e0

IN OTHER WORDS, the shared_ptr obtained via make_shared calls its destructor but not the operator delete while the shared_ptr obtained via new calls both destructor of Widget and operator delete of Widget..

WHY IS THIS different behaviour?

Thanks,
Juan
When you use make_shared it allocates one piece of memory that contains both the Widget object and the reference counter. That means the Widget object can't be allocated and deallocated directly using new and delete.
Last edited on
got it, thanks!!
Topic archived. No new replies allowed.