allocate_shared
, make_shared
, and make_unique
all initialize the underlying object by performning something equivalent to new T(args...)
. In the zero-argument case, that reduces to new T()
- which is to say, it performs value initialization. Value initialization in many cases (including scalar types like int
and char
, arrays of them, and aggregates of them) performs zero initialization - which is to say, that is actual work being done to zero out a bunch of data.
Maybe you want that and that is important to your application, maybe you don't. From P1020R1, the paper that introduced the functions originally named make_unique_default_init
, make_shared_default_init
, and allocate_shared_default_init
(these were renamed from meow_default_init
to meow_for_overwrite
during the national ballot commenting process for C++20):
It is not uncommon for arrays of built-in types such as unsigned char
or double
to be immediately initialized by the user in their entirety after allocation. In these cases, the value initialization performed by allocate_shared
, make_shared
, and make_unique
is redundant and hurts performance, and a way to choose default initialization is needed.
That is, if you were writing code like:
auto buffer = std::make_unique<char[]>(100);
read_data_into(buffer.get());
The value initialization performed by make_unique
, which would zero out those 100 bytes, is completely unnecessary since you're immediately overwriting it anyway.
The new meow_for_overwrite
functions instead perform default initialization since the memory used will be immediately overwritten anyway (hence the name) - which is to say the equivalent of doing new T
(without any parentheses or braces). Default initialization in those cases I mentioned earlier (like int
and char
, arrays of them, and aggregates of them) performs no initialization, which saves time.
For class types that have a user-provided default constructor, there is no difference between value initialization and default initialization: both would just invoke the default constructor. But for many other types, there can be a large difference.