std::make_shared is a function in C++ that is used to create a shared pointer (std::shared_ptr) to an object. The primary purposes of using std::make_shared are:
-
Memory Efficiency: It allocates memory for both the object and the control block (which manages the reference count) in a single allocation, reducing memory overhead and fragmentation.
-
Exception Safety: If an exception is thrown during the construction of the object,
std::make_sharedensures that no memory leak occurs, as it manages the memory allocation and deallocation automatically. -
Simplified Syntax: It provides a cleaner and more concise way to create shared pointers compared to using
newdirectly.
Here is an example of how to use std::make_shared:
#include <iostream>
#include <memory>
class MyClass {
public:
MyClass() {
std::cout << "MyClass constructor called." << std::endl;
}
~MyClass() {
std::cout << "MyClass destructor called." << std::endl;
}
};
int main() {
std::shared_ptr<MyClass> ptr = std::make_shared<MyClass>();
// Use ptr as needed
return 0; // MyClass destructor will be called automatically when ptr goes out of scope
}
In this example, std::make_shared<MyClass>() creates a shared pointer to an instance of MyClass, ensuring efficient memory management.
