Unique pointer
unique_ptr is a smart pointer provided by the C++ Standard Library in the
Code Example
Explanation
Create a unique pointerunique_ptr<MyClass> ptr1 = make_unique<MyClass>("unique pointer example");
- We create a unique_ptr named ptr1 that manages a new MyClass object initialized with the string "unique pointer example".
- make_unique is a helper function that simplifies the creation of a unique_ptr
Moving Ownership:
unique_ptr<MyClass> ptr2 = move(ptr1); // move the handle from original to new pointer
- We transfer ownership of the object from ptr1 to ptr2 using the move function.
- After this, ptr1 no longer owns the object, and attempting to access it will result in undefined behavior.
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.