How to Create a shared_ptr in C++?
Last Updated :
15 Feb, 2024
A std::shared_pointer is a smart pointer introduced in C++11 that manages the lifetime of a dynamically allocated object through reference counting. In this article, we will learn how to create a shared_pointer.
shared_ptr in C++
A std::shared_pointer can be created by using the std::make_shared method which is defined in <memory> header in C++. Use the below syntax to create a shared_ptr.
Syntax to Create shared_ptr in C++
auto sharedPtr = make_shared<Type>(constructor_arguments);
Here,
Type
is the type of the object that we want to allocate and manage with the std::shared_ptr
.
constructor_arguments
are the arguments that are passed to the constructor of Type
.
C++ Program to Create shared_ptr
The below demonstrates how we can create a shared_ptr using the make_shared function and then access a member function of the class.
C++
#include <iostream>
#include <memory>
using namespace std;
class MyClass {
public :
MyClass() { cout << "MyClass Constructor\n" ; }
~MyClass() { cout << "MyClass Destructor\n" ; }
void printHello() const { cout << "Hello!" << endl; }
};
int main()
{
shared_ptr<MyClass> mySharedPtr
= make_shared<MyClass>();
mySharedPtr->printHello();
return 0;
}
|
Output
MyClass Constructor
Hello!
MyClass Destructor
Note: We can also create shared_ptr by directly using std::shared_ptr
constructor.
Share your thoughts in the comments
Please Login to comment...