Sobes.tech
Junior — Middle

In which cases is it not recommended to use the std::make_shared function in C++?

sobes.tech AI

Answer from AI

The std::make_shared function in C++ is generally recommended for creating objects with managed lifetime through std::shared_ptr, as it is efficient and safe. However, there are situations where its use is not recommended:

  • When a custom allocator or custom memory management is needed. make_shared uses a single allocator for the object and control block, which is not always suitable.

  • When the object needs to have a non-standard lifecycle or be placed in special memory (e.g., shared memory).

  • If the object must be created using placement new or with special initialization that cannot be passed through make_shared.

  • When managing the object and control block separately is necessary (e.g., for weak references with special behavior).

In such cases, it is better to use the shared_ptr constructor directly or other smart pointer creation methods.