You are expected to use std::make_shared
to ensure that block with counters is stored next to data. Unfortunately internally std::make_shared<T>
uses zero initialization for T
(i.e. uses T()
to initialize data block). Is there any way to trick it into using default initialization? I know I can use std::shared_ptr<T>( new T, [](auto p){delete p;})
, but I'll end up with two allocations here (data and counter blocks won't be next to each other).
Create a derived class to enforce trivial construction.
struct D : T {
D() {} // Non-trivial constructor. Default-initialize T, which may be trivial.
};
Construct the derived class but assign it to the shared pointer you want.
std::shared_ptr< T > p = std::make_shared< D >();
Demo.
Note that this is type-safe with respect to the destructor. shared_ptr
always performs type erasure and uses dynamic dispatch before the destructor call, even for simple POD objects.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With