Sobes.tech
Junior — Middle

How is the smart pointer unique_ptr implemented and how does it manage object ownership?

sobes.tech AI

Answer from AI

unique_ptr is a smart pointer in C++ that provides exclusive ownership of a dynamically allocated object. It guarantees that the object will be automatically deleted when the unique_ptr goes out of scope, preventing memory leaks.

Features of unique_ptr:

  • Ownership of the object can only be held by one unique_ptr at a time.
  • Copying unique_ptr is prohibited (copy constructor is deleted), but moving (move semantics) is allowed.
  • When moved, ownership is transferred to the new pointer, and the old one becomes empty.

Example usage:

#include <memory>
#include <iostream>

struct Foo {
    Foo() { std::cout << "Foo created\n"; }
    ~Foo() { std::cout << "Foo destroyed\n"; }
    void bar() { std::cout << "Method bar called\n"; }
};

int main() {
    std::unique_ptr<Foo> p1 = std::make_unique<Foo>();
    p1->bar();

    // Transfer ownership
    std::unique_ptr<Foo> p2 = std::move(p1);
    if (!p1) {
        std::cout << "p1 no longer owns the object\n";
    }
    p2->bar();

    // The object will be automatically deleted when p2 goes out of scope
    return 0;
}

Thus, unique_ptr helps manage resources safely without the need to explicitly call delete.