*_for_overwrite: a less known C++20 feature

published at 23.10.2022 20:53 by Jens Weller
Save to Instapaper Pocket

When I looked up make_unique for this weeks Meeting C++ blogroll highlight, I found a surprise.

This weeks blogroll highlight is Why is there a make_unique? Why not just overload the unique_ptr constructor? from Raymond Chens blog The old new thing.

So when preparing this, I looked up make_unique on cppreference, but I did not expect a C++20 feature to be on that page. One I wasn't even aware it existed. My expectation had been to only find make_unique on this page, but there it was: make_unique_for_overwrite. A quick glance around found that also make_shared and allocate_shared have a version of this since C++20. And looking at the compiler status page, GCC and MSVC currently implement these.

Allocating default-initialized heap variables for smart pointers

These functions serve the purpose of allocating a default-initialized value on the heap for a smart pointer. There are two versions: one without arguments for a single variable, and a version that takes a size_t for allocating an array of this size. Both return a unique or shared_pointer to this allocation. A third overload exists with (Args&&... args), which is deleted. Ensuring you can only call this function with no arguments or a size_t convertible type.

While a class type will have its default constructor called, a scalar-type like an int will be uninitialized. This is an important distinction, as make_unique/shared and allocate_shared do zero out the memory for these. So for_overwrite gives you now a version which returns the raw and untouched allocated memory. This can be useful when you have to hand over this memory for initialization to some other function after construction, so that the zeroing out of this memory would be an overhead.

C++23 makes these constexpr, so you can use this for compile time allocations too.

Join the Meeting C++ patreon community!
This and other posts on Meeting C++ are enabled by my supporters on patreon!