Sobes.tech
Junior — Middle

How is resource assignment performed for an object of std::unique_ptr?

sobes.tech AI

Answer from AI

std::unique_ptr is a smart pointer that owns a unique resource (usually a dynamically allocated object). Resource assignment to std::unique_ptr occurs through move semantics, not copying, because copying is disallowed for unique pointers.

When you assign one std::unique_ptr to another, ownership of the resource is transferred from the source to the receiver. After this, the original pointer becomes empty (null), and the new one owns the resource.

Example:

#include <memory>
#include <iostream>

int main() {
    std::unique_ptr<int> ptr1 = std::make_unique<int>(42);
    std::unique_ptr<int> ptr2;

    // Transfer ownership of the resource from ptr1 to ptr2
    ptr2 = std::move(ptr1);

    if (!ptr1) {
        std::cout << "ptr1 is now empty" << std::endl;
    }
    std::cout << "ptr2 owns the value: " << *ptr2 << std::endl;

    return 0;
}

Thus, assignment for std::unique_ptr is implemented via the move operator, ensuring exclusive ownership of the resource.

How is resource assignment performed for an object of… - sobes.tech