How to Create a shared_ptr in C++?
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 thestd::shared_ptr
.constructor_arguments
are the arguments that are passed to the constructor ofType
.
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++
// C++ program to create shared_ptr #include <iostream> #include <memory> using namespace std; // defining my class class MyClass { public : // constructor of myClass MyClass() { cout << "MyClass Constructor\n" ; } // destructor of myClass ~MyClass() { cout << "MyClass Destructor\n" ; } void printHello() const { cout << "Hello!" << endl; } }; int main() { // Creating a shared_ptr using make_shared shared_ptr<MyClass> mySharedPtr = make_shared<MyClass>(); // Use the shared_ptr mySharedPtr->printHello(); // The MyClass instance will be automatically destroyed // when mySharedPtr goes out of scope return 0; } |
Output
MyClass Constructor Hello! MyClass Destructor
Note: We can also create shared_ptr by directly using
std::shared_ptr
constructor.
Contact Us