When using std::make_shared<C>
the class overloaded new/delete operators are not called.
When using std::shared_ptr<C>
, std::unique_ptr<C>
& std::make_unique<C>
the class overloaded new/delete operators are used.
When looking at the documentation it's perfectly correct and well documented.
cppreference explains the behavior:
std::make_shared
uses ::new, so if any special behavior has been set up using a class-specific operator new, it will differ fromstd::shared_ptr<T>(new T(args...))
.
Below is some pseudo-code to better highlight the behavior:
#include <memory>
class C {
public:
void* operator new(size_t size) {
void* p = ::operator new(size);
std::cout << "C::new() -> " << p << "\n";
return p;
}
void operator delete(void* p) {
std::cout << "C::delete() -> " << p << "\n";
::operator delete(p);
}
};
std::shared_ptr<C> ptr = std::make_shared<C>();
From an external point of view, it seems inconsistent and error prone. Overloading class new/delete operators should always be used.
So, what is the rationale of the behavior?
And, where is the C++ specification detailing the std::make_shared
behavior?
Thanks for your help.
std::allocate_shared
for this – Preselector