0
0
CppConceptBeginner · 3 min read

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.

cpp
#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;
}
Output
Value: 42 Use count: 1
🎯

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_shared creates an object and its shared pointer in one step.
  • It is more efficient than using new with shared_ptr separately.
  • 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.
It improves performance by combining memory allocation for object and control block.
Use it to share ownership of objects without manual memory management.
It helps prevent memory leaks by automatic cleanup when no owners remain.