Junior — Middle
Can you explain the purpose and operation of the make_shared function in C++ and how it compares to using new for creating smart pointers?
sobes.tech AI
Answer from AI
The make_shared function in C++ is used to create an object and a std::shared_ptr smart pointer to that object simultaneously. It allocates memory once for both the object and the control block, which improves efficiency.
Advantages of make_shared compared to using new and the shared_ptr constructor directly:
- Memory allocation optimization:
make_sharedallocates a single memory block for the object and control block, whereas usingnewandshared_ptrallocates two separate blocks. - Safety:
make_sharedprevents memory leaks if theshared_ptrconstructor throws an exception afternew. - Convenience: The code becomes shorter and cleaner.
Example:
#include <memory>
std::shared_ptr<int> p1 = std::make_shared<int>(42); // Creates an int object with value 42
// Similarly, but less efficiently:
std::shared_ptr<int> p2(new int(42));
It is recommended to use make_shared in most cases for creating shared_ptr.