Search code examples
c++shared-ptrc++20

When to use std::make_shared_for_overwrite?


C++20 introduces new function std::make_shared_for_overwrite() in addition to std::make_shared(): https://en.cppreference.com/w/cpp/memory/shared_ptr/make_shared

Why old make_shared was not enough and in what situation one needs to use new function?


Solution

  • std::make_shared() value initialises the object(s) it creates, which might be an unnecessary step if you intend to assign values over them later.

    std::make_shared_for_overwrite() default initialises the object(s) it creates.

    The difference only matters for (sub-)objects of fundamental types, where there is no initialiser.

    std::make_shared<int[1000][1000]>() will allocate and zero a million ints std::make_shared_for_overwrite<int[1000][1000]>() will allocate a million ints