Is there a way to trick std :: make_shared into using default initialization?

You should use std::make_shared to ensure that the block with counters is stored next to the data. Unfortunately inside std::make_shared<T> uses zero initialization for T (i.e. uses T() to initialize a data block). Is there a way to trick him into using default initialization? I know that I can use std::shared_ptr<T>( new T, [](auto p){delete p;}) , but here I get two distributions (data and counter blocks will not be next to each other).

+5
source share
1 answer

Create a derived class to provide a trivial construct.

 struct D : T { D() {} // Non-trivial constructor. Default-initialize T, which may be trivial. }; 

Build a derived class, but assign it to the generic pointer you want.

 std::shared_ptr< T > p = std::make_shared< D >(); 

Demo version

Note that this is type safe with respect to the destructor. shared_ptr always erases styles and uses dynamic dispatch before calling the destructor, even for simple POD objects.

+9
source

Source: https://habr.com/ru/post/1263651/


All Articles