Code Snippets
/

unique_ptr vs shared_ptr Cheat Sheet

unique_ptr vs shared_ptr Cheat Sheet

Smart pointers are how modern C++ handles ownership without naked `new`/`delete`. This snippet contrasts `std::unique_ptr` (single-owner, zero overhead) with `std::shared_ptr` (reference-counted, multi-owner) and shows when each is the right choice. The default rule: pick `unique_ptr` unless you can prove you genuinely need shared ownership.

C++
Medium
3 snippets
cpp-smart-pointers
cpp-memory-management
cpp-raii

507 views

6

#include <iostream>
#include <memory>
#include <vector>
#include <string>

struct Resource {
    std::string name;
    Resource(std::string n) : name(std::move(n)) {
        std::cout << "acquire " << name << "\n";
    }
    ~Resource() { std::cout << "release " << name << "\n"; }
};

int main() {
    // Prefer make_unique over `unique_ptr<T>(new T(...))`: exception-safe + concise.
    std::unique_ptr<Resource> a = std::make_unique<Resource>("A");
    std::cout << "name=" << a->name << "\n";

    // unique_ptr CANNOT be copied; only moved.
    std::unique_ptr<Resource> b = std::move(a);
    std::cout << "a is " << (a ? a->name : "null") << "\n";
    std::cout << "b is " << b->name << "\n";
    // ~Resource("A") fires when b leaves scope.
    return 0;
}

std::unique_ptr<T> is a single-owner smart pointer with zero runtime overhead compared to a raw pointer; the destructor calls delete automatically. Move-only semantics mean ownership transfers explicitly: after std::move(a), a is null and b owns the object. Use unique_ptr for almost every dynamic allocation in modern C++; the moment you reach for new, ask yourself whether make_unique would do. Pass unique_ptr by value to transfer ownership into a function, or pass the raw T* (or T&) when only borrowing for the duration of a call.