std::shared_ptr shares the ownership of the resource. They have two handles. One for the resource and one for the reference counter. By copying a
std::shared_ptr, the reference count is increased by one. It is decreased by one if the
std::shared_ptr goes out of scope. If the reference counter becomes the value 0 and therefore there is no
std::shared_ptr referencing the resource, the C++ runtime automatically releases the resource. The release of the resource takes place at exactly the time at which the last
std::shared_ptr goes out of scope. The C++ runtime guarantees that the call of the reference counter is an atomic operation. Because of this management,
std::shared_ptr uses more time and memory than a raw pointer or
In the following table are the methods of
|Returns a pointer to the resource.
|Returns the delete function
|Resets the resource
|Swaps the resources.
|Checks if the
std::shared_ptr is the exclusive owner of the resource.
|Returns the value of the reference counter.
Methods of `std::shared_ptr`
The helper function std::make_shared creates the resource and returns it in a
std::shared_ptr. You should use
std::make_shared instead of the direct creation of a
std::make_shared is a lot faster.
The following code sample shows a typical use case of a