Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 470
Fedor Avatar asked Apr 17 '26 16:04

Fedor


1 Answers

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

like image 82
Caleth Avatar answered Apr 19 '26 15:04

Caleth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!