Syntax of std::shared_ptr

The shared_ptr of type T can be declared as:

std::shared_ptr <T> ptr_name;

Initialization of shared_ptr Objects

We can initialize the shared_ptr using the following methods:

1. Initialization using a New Pointer

shared_ptr<T> ptr (new T());
shared_ptr<T> ptr = make_shared<T> (new T());

2. Initialization using existing Pointer

shared_ptr<T> ptr(already_existing_pointer);
shared_ptr<T> ptr = make_shared(already_existing_pointer);

shared_ptr in C++

std::shared_ptr is one of the smart pointers introduced in C++11. Unlike a simple pointer, it has an associated control block that keeps track of the reference count for the managed object. This reference count is shared among all the copies of the shared_ptr instances pointing to the same object, ensuring proper memory management and deletion.

Shared Pointer in C++

Similar Reads

Syntax of std::shared_ptr

The shared_ptr of type T can be declared as:...

Member Methods of shared_ptr

Following are some members associated with shared_ptr:...

Examples of std::shared_ptr

Example 1:...