What is make_shared in C++: Simple Explanation and Example
make_shared is a C++ function that creates an object and returns a std::shared_ptr managing it in one step. It is safer and more efficient than creating a shared pointer with new because it combines allocation and construction.How It Works
Imagine you want to share a toy with friends, but you want to keep track of how many friends are playing with it so you know when to put it away. make_shared in C++ works like that: it creates an object and a smart pointer that counts how many owners it has.
When you use make_shared, it allocates memory for both the object and the control block (which keeps the count) in one go. This is like buying a toy and a box for it together, making it faster and safer.
Because it combines these steps, make_shared reduces the chance of errors and improves performance compared to creating a shared pointer by calling new separately.
Example
This example shows how to create a shared pointer to an integer using make_shared and how it automatically manages memory.
#include <iostream> #include <memory> int main() { std::shared_ptr<int> ptr = std::make_shared<int>(42); std::cout << "Value: " << *ptr << std::endl; std::cout << "Use count: " << ptr.use_count() << std::endl; return 0; }
When to Use
Use make_shared whenever you want to create a shared pointer to manage a dynamically allocated object safely and efficiently. It is ideal when multiple parts of your program need to share ownership of the same object without worrying about manual memory management.
For example, in a graphics program, multiple objects might share a texture. Using make_shared ensures the texture stays alive as long as anyone needs it and is cleaned up automatically when no longer used.
Key Points
make_sharedcreates an object and its shared pointer in one step.- It is more efficient than using
newwithshared_ptrseparately. - It helps avoid memory leaks by managing object lifetime automatically.
- Use it when multiple owners share the same object.
Key Takeaways
make_shared safely creates and manages shared objects in one step.