Copying and Moving unique_ptr in C++

In C++, a unique_ptr is a smart pointer that owns and manages dynamically allocated memory. It automatically deletes the linked memory when the unique_ptr goes out of scope. One key aspect of unique_ptr is ownership uniqueness, meaning that there can only be one unique_ptr pointing to any given resource at a time. This uniqueness is enforced by the language to prevent multiple unique_ptrs from managing the same resource, which would lead to issues like double deletion.

Can a Unique_ptr be copied?

Since unique_ptrs enforce unique ownership, you cannot copy a unique_ptr. Attempting to do so will result in a compilation error. Here’s a code snippet that shows what happens when you try to copy a unique_ptr:

// unique_ptr pointing to an int with value 12
std::unique_ptr<int> ptrObj(new int(12));  

// Attempting to copy will fail at compile time
// std::unique_ptr<int> anotherPtr = ptrObj; // This will not compile

Moving Unique_ptr is allowed

Although copying a unique_ptr object is not allowed, but you can transfer ownership of underlying memory resource managed by a unique_ptr to another unique_ptr using the std::move() function. This process is called “moving” and effectively renders the source unique_ptr empty (i.e., it becomes nullptr) and the destination unique_ptr now owns the resource (memory).

Here’s an example of how to move a unique_ptr:

#include <iostream>
#include <memory>

int main()
{
    // ptr is managing a new int with value 11
    std::unique_ptr<int> ptr(new int(11));  

    // Move ptr to another unique_ptr
    std::unique_ptr<int> anotherPtr = std::move(ptr);

    // ptr is now empty, and anotherPtr manages the resource
    if (!ptr) {
        std::cout << "ptr is now nullptr" << std::endl;
    }

    if(anotherPtr)
    {
        std::cout << "anotherPtr points to memory with value: " << *anotherPtr << std::endl;
    }

    return 0;
}

Output:

ptr is now nullptr
anotherPtr points to memory with value: 11

Summary

In Modern C++, the Smart Pointer unique_ptr ensures that only one smart pointer can manage a given resource at a time. You cannot copy a unique_ptr but you can transfer its ownership to another unique_ptr using std::move(). This mechanism is important for maintaining resource safety and preventing memory leaks in C++ programs. Remember, once moved, the original unique_ptr will be reset to nullptr, and attempting to use it will be as if it points to no resource at all.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top