How do I use unique_ptr, shared_ptr, and weak_ptr in C++?

In C++, smart pointers are an important part of memory management that help in automatically handling resource management. The three main types of smart pointers are unique_ptr, shared_ptr, and weak_ptr.

unique_ptr

A unique_ptr is a smart pointer that owns a dynamically allocated object and ensures that there is only one unique pointer to that object. When the unique_ptr goes out of scope, the associated object is destroyed. This prevents memory leaks and deallocation issues.

shared_ptr

A shared_ptr allows multiple pointers to share ownership of the same dynamically allocated object. The object is destroyed when the last shared_ptr pointing to it is destroyed or reset. This is useful in scenarios where ownership needs to be shared across different parts of the program.

weak_ptr

A weak_ptr provides a way to refer to a shared_ptr object without affecting its reference count. This can help prevent circular references and memory leaks in scenarios where two objects reference each other.

Example

#include <iostream> #include <memory> class MyClass { public: MyClass() { std::cout << "MyClass constructed." << std::endl; } ~MyClass() { std::cout << "MyClass destructed." << std::endl; } }; int main() { // Using unique_ptr std::unique_ptr uniquePtr = std::make_unique(); // Using shared_ptr std::shared_ptr sharedPtr1 = std::make_shared(); std::shared_ptr sharedPtr2 = sharedPtr1; // shared ownership // Using weak_ptr std::weak_ptr weakPtr = sharedPtr1; // does not affect reference count return 0; }

unique_ptr shared_ptr weak_ptr smart pointers C++ memory management