Unique pointer

unique_ptr is a smart pointer provided by the C++ Standard Library in the header. It is used to manage the lifetime of dynamically allocated objects, ensuring that the allocated memory is automatically freed when the unique_ptr goes out of scope. Unlike regular pointers, a unique_ptr has sole ownership of the object it points to, meaning no two unique_ptr instances can own the same object.

Code Example


Explanation

Create a unique pointer
unique_ptr<MyClass> ptr1 = make_unique<MyClass>("unique pointer example");

Moving Ownership:
unique_ptr<MyClass> ptr2 = move(ptr1); // move the handle from original to new pointer

Conclusion

unique_ptr is a powerful tool for managing dynamic memory in C++. It ensures that memory is properly released when it is no longer needed and prevents memory leaks. However, it enforces strict ownership rules, making it impossible to have multiple owners of the same object. This makes unique_ptr suitable for scenarios where exclusive ownership is required.