What is unique_ptr in C++: Simple Explanation and Usage
unique_ptr is a smart pointer in C++ that owns and manages a dynamically allocated object exclusively. It automatically deletes the object when the unique_ptr goes out of scope, preventing memory leaks.How It Works
Imagine you have a box that holds a single valuable item, and only you have the key to open it. This box represents a unique_ptr, and the valuable item is a dynamically created object in memory. The unique_ptr ensures that only one owner exists for that object, so no one else can accidentally change or delete it.
When the unique_ptr is destroyed, like when the box is thrown away, it automatically deletes the object inside. This means you don't have to remember to free the memory yourself, which helps avoid common mistakes like forgetting to delete or deleting twice.
Example
This example shows how to create a unique_ptr to manage a dynamically allocated integer. When the pointer goes out of scope, it deletes the integer automatically.
#include <iostream> #include <memory> int main() { std::unique_ptr<int> ptr = std::make_unique<int>(42); std::cout << "Value inside unique_ptr: " << *ptr << std::endl; // No need to delete ptr manually return 0; }
When to Use
Use unique_ptr when you want a single owner for a dynamically allocated object and want to ensure automatic cleanup. It is perfect for managing resources that should not be shared, like file handles or unique data structures.
For example, if you create an object inside a function and want to return ownership to the caller without worrying about manual deletion, unique_ptr is a safe and clear choice.
Key Points
- Exclusive ownership: Only one
unique_ptrcan own the object at a time. - Automatic cleanup: Deletes the object when the pointer goes out of scope.
- Non-copyable: You cannot copy a
unique_ptr, but you can move it. - Safe memory management: Helps prevent memory leaks and dangling pointers.
Key Takeaways
unique_ptr manages a single object's lifetime automatically and exclusively.unique_ptr cannot be copied but can be moved to transfer ownership safely.