Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c++11

c++14

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).

like image 916
C.M. Avatar asked Feb 01 '17 06:02

C.M.


1 Answers

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.

like image 103
Potatoswatter Avatar answered Oct 24 '22 15:10

Potatoswatter