Welcome to our comprehensive guide on make_shared in C++! This tutorial is designed for both beginners and intermediate learners, providing a deep dive into the concept. Let's get started!
In C++, make_shared is a function introduced in C++11 that creates shared ownership of an object of a given type using shared_ptr. It's a powerful tool for memory management, especially in multithreaded programs.
Shared ownership is crucial when multiple parts of a program need to share an object without worrying about deleting it prematurely. make_shared ensures that the object is created, and its memory is managed correctly, even in multithreaded environments.
The syntax for make_shared is as follows:
std::shared_ptr<type> ptr = std::make_shared<type>(args...);Here, type is the data type of the object you want to create, and args... are the arguments you'd pass to the constructor of that type.
Let's create a simple example to illustrate the usage of make_shared. We'll create a Person class and share an instance of it using make_shared.
#include <iostream>
#include <memory>
#include <string>
class Person {
public:
Person(const std::string& name) : _name(name) {}
void Introduce() {
std::cout << "Hello, I'm " << _name << ".\n";
}
private:
std::string _name;
};
int main() {
std::shared_ptr<Person> person = std::make_shared<Person>("Alice");
person->Introduce();
// Another part of the program can also access the shared person
std::shared_ptr<Person> another = person;
another->Introduce();
return 0;
}In this example, we first define a Person class with a constructor and an Introduce method. In the main function, we create a shared_ptr to a Person object named Alice using make_shared. We then print Alice's introduction, and another part of the program accesses the same shared Person object.
One important aspect of make_shared is that the object is not destroyed until all shared_ptr instances pointing to it are destroyed. This ensures that the object is not deleted prematurely in a multithreaded environment.
Each shared_ptr object that points to the same memory location shares a reference count, which is increased and decreased as new shared_ptr instances are created and destroyed. The shared count represents the number of shared_ptr instances pointing to the same object.
What is the purpose of `make_shared` in C++?