Junior — Middle
What is the main purpose of using the make_shared function and what are its advantages?
sobes.tech AI
Answer from AI
The make_shared function in C++ is used to create an object managed by a std::shared_ptr smart pointer. Its main goal is to efficiently and safely allocate memory for the object and the control block in a single allocation, reducing overhead and increasing performance.
Advantages of make_shared:
- Memory allocation optimization: one memory block is allocated for both the object and the reference count, unlike two separate allocations when using
shared_ptrwithnew. - Safety: it eliminates the risk of memory leaks, even if the object's constructor throws an exception.
- Convenience: the syntax is simpler and cleaner.
Example usage:
#include <memory>
struct MyClass {
int x;
MyClass(int val) : x(val) {}
};
int main() {
auto ptr = std::make_shared<MyClass>(10); // Creates a shared_ptr to a MyClass object with x=10
}