Sobes.tech
Junior — Middle

Explain the mechanism of the smart pointer std::unique_ptr in C++ and its features

sobes.tech AI

Answer from AI

std::unique_ptr is a smart pointer in C++ that provides exclusive ownership of an object. Its features:

  • Exclusive ownership: only one unique_ptr can own the object at a time.
  • Automatic memory release: when the unique_ptr is destroyed, the object's destructor is called, and memory is freed.
  • Cannot be copied, but can be moved (std::move), allowing transfer of ownership.

Example usage:

#include <memory>
#include <iostream>

int main() {
    std::unique_ptr<int> ptr1 = std::make_unique<int>(10);
    std::cout << *ptr1 << std::endl; // outputs 10

    // std::unique_ptr<int> ptr2 = ptr1; // Error: copying is prohibited
    std::unique_ptr<int> ptr2 = std::move(ptr1); // Transfer ownership

    if (!ptr1) {
        std::cout << "ptr1 no longer owns the object" << std::endl;
    }

    std::cout << *ptr2 << std::endl; // outputs 10
}

Thus, unique_ptr helps prevent memory leaks and ensures resource ownership safety.