What is the purpose of std::make_shared?

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:

  1. 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.

  2. Exception Safety: If an exception is thrown during the construction of the object, std::make_shared ensures that no memory leak occurs, as it manages the memory allocation and deallocation automatically.

  3. Simplified Syntax: It provides a cleaner and more concise way to create shared pointers compared to using new directly.

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.

0 Comments

no data
Be the first to share your comment!