C++ Unique Pointer

A unique_ptr in C++ is a smart pointer that owns and manages a dynamically allocated object exclusively. It ensures that the object is automatically deleted when the unique_ptr goes out of scope, preventing memory leaks. Only one unique_ptr can own a particular resource at a time.

1. What is a Unique Pointer?

A unique_ptr is a type of smart pointer in C++ that maintains exclusive ownership of a dynamically allocated object. It automatically deletes the object when the unique_ptr is destroyed, making memory management safer and easier.

C++
Basic example of unique_ptr
#include <iostream>
#include <memory>
using namespace std;

int main() {
    unique_ptr<int> ptr = make_unique<int>(10); // create unique_ptr
    cout << "Value: " << *ptr << endl;
    // No need to delete ptr, automatic cleanup
    return 0;
}

2. Advantages of unique_ptr

1. Automatic Memory Management: No need to manually delete. 2. Prevents Dangling Pointers: Ownership cannot be copied accidentally. 3. Exclusive Ownership: Guarantees a single owner for a resource. 4. Exception Safety: Automatic cleanup in case of exceptions. 5. Lightweight: No reference counting overhead unlike shared_ptr.

3. Example of unique_ptr Usage

C++
unique_ptr ownership transfer using std::move
#include <iostream>
#include <memory>
using namespace std;

int main() {
    unique_ptr<int> ptr1 = make_unique<int>(42);
    cout << "ptr1 value: " << *ptr1 << endl;

    // Transfer ownership to ptr2
    unique_ptr<int> ptr2 = move(ptr1);

    if(!ptr1) cout << "ptr1 is now null" << endl;
    cout << "ptr2 value: " << *ptr2 << endl;

    return 0;
}

Ownership can be transferred using std::move. After moving, the original unique_ptr becomes null.

4. Things to Be Careful About

1. Cannot copy a unique_ptr; must use std::move to transfer ownership. 2. Do not store unique_ptr in containers that require copy semantics without moving. 3. Avoid raw pointer access that could outlive the unique_ptr’s scope.

5. Best Practices

1. Prefer make_unique over direct new to avoid exceptions. 2. Use unique_ptr whenever exclusive ownership is required. 3. Avoid mixing raw pointers and unique_ptr for the same resource. 4. Use std::move carefully to transfer ownership. 5. Combine with containers and algorithms that support move semantics.

Conclusion

unique_ptr is a safe and efficient smart pointer in C++ that enforces exclusive ownership of dynamically allocated objects. By using unique_ptr, developers can prevent memory leaks, dangling pointers, and simplify memory management in modern C++ code.