Sobes.tech
Junior — Middle

Explain the purpose and application of smart pointers with unique ownership in C++.

sobes.tech AI

Answer from AI

Smart pointers with unique ownership (e.g., std::unique_ptr in C++) are designed for automatic management of the lifetime of dynamically allocated objects. They guarantee that the object will be destroyed exactly once, when the last owner (the unique pointer) goes out of scope or is explicitly released.

Main advantages:

  • Prevent memory leaks by automatically calling delete on the managed object.
  • Disallow copying, which prevents double deletion.
  • Support transfer of ownership through move semantics.

Example usage:

#include <memory>
#include <iostream>

struct Resource {
    Resource() { std::cout << "Resource acquired\n"; }
    ~Resource() { std::cout << "Resource destroyed\n"; }
};

int main() {
    std::unique_ptr<Resource> ptr1 = std::make_unique<Resource>();
    // std::unique_ptr<Resource> ptr2 = ptr1; // Error: cannot copy
    std::unique_ptr<Resource> ptr2 = std::move(ptr1); // Transfer ownership
    // ptr1 is now nullptr
}

Thus, unique_ptr provides safe and efficient resource management without the need to manually call delete.