Sobes.tech
Junior — Middle

Explain the differences between smart pointers std::unique_ptr and std::shared_ptr in C++.

sobes.tech AI

Answer from AI

std::unique_ptr and std::shared_ptr are smart pointers in C++ that manage object lifetime but have different ownership semantics:

  • std::unique_ptr owns an object exclusively. It cannot be copied, only moved. When a unique_ptr is destroyed, the object is deleted. It is used when strict ownership control is needed and shared usage is not.

  • std::shared_ptr implements reference counting. Multiple shared_ptrs can own the same object. The object is deleted when the last shared_ptr owning it is destroyed or reset.

Example:

#include <memory>
#include <iostream>

int main() {
    std::unique_ptr<int> uptr = std::make_unique<int>(10);
    // std::unique_ptr<int> uptr2 = uptr; // Error: cannot copy
    std::unique_ptr<int> uptr2 = std::move(uptr); // transfer ownership

    std::shared_ptr<int> sptr1 = std::make_shared<int>(20);
    std::shared_ptr<int> sptr2 = sptr1; // copy, increases reference count

    std::cout << *sptr1 << " " << *sptr2 << std::endl;
}

This demonstrates the ownership differences clearly.