#include#include int main() { // Create a shared_ptr object to an integer std::shared_ptr ptr = std::make_shared (42); // Use the pointer std::cout << "Value of ptr: " << *ptr << std::endl; }
#include#include void customDeleter(int* pointer) { std::cout << "Deleting pointer..." << std::endl; delete[] pointer; } int main() { // Create a shared_ptr object to an array of integers with custom deleter function std::shared_ptr ptr(new int[5], customDeleter); // Use the pointer ptr.get()[0] = 42; std::cout << "Value of ptr: " << ptr.get()[0] << std::endl; }
#includeThe examples above demonstrate the use of shared_ptr for automatic memory management. The library used in these examples is the standard C++ library.#include class MyClass { public: MyClass() { std::cout << "MyClass constructor" << std::endl; } ~MyClass() { std::cout << "MyClass destructor" << std::endl; } }; int main() { // Create a shared_ptr object to a dynamically allocated MyClass object std::shared_ptr ptr1 = std::make_shared (); // Create another shared_ptr object that shares ownership with ptr1 std::shared_ptr ptr2 = ptr1; // Use the pointers std::cout << "Count of shared_ptr objects: " << ptr1.use_count() << std::endl; }