c++c++20smart-pointersunique-ptr

What does std::make_unique_for_overwrite() do vis-a-vis std::make_unique()?


It appears that in C++20, we're getting some additional utility functions for smart pointers, including:

template<class T> unique_ptr<T> make_unique_for_overwrite();
template<class T> unique_ptr<T> make_unique_for_overwrite(size_t n);

and the same for std::make_shared with std::shared_ptr. Why aren't the existing functions:

template<class T, class... Args> unique_ptr<T> make_unique(Args&&... args); // with empty Args
template<class T> unique_ptr<T> make_unique(size_t n);

enough? Don't the existing ones use the default constructor for the object?

Note: In earlier proposals of these functions, the name was make_unique_default_init().


Solution

  • These new functions are different:

    This is a feature of plain vanilla pointers which was not available with the smart pointer utility functions: With regular pointers you can just allocate without actually initializing the pointed-to value:

    new int
    

    For unique/shared pointers you could only achieve this by wrapping an existing pointer, as in:

    std::unique_ptr<int[]>(new int[n])
    

    now we have a wrapper function for that.

    Note: See the relevant ISO C++ WG21 proposal as well as this SO answer