The C++ std::shared_ptr class is a smart pointer that manages the lifecycle of an object. It makes it easy to share objects between different pieces of code without having to worry about memory management.
Example 1: Creating a shared_ptr
#include
int main() {
std::shared_ptr ptr(new int); // create a shared_ptr to an int
return 0;
}
This example creates a shared_ptr to an int. The shared_ptr takes ownership of the int and will automatically delete it when the last shared_ptr that points to it goes out of scope.
Package library: Standard Template Library (STL)
Example 2: Sharing an object
#include
#include
struct Object {
int value;
};
int main() {
std::shared_ptr