C/C++ Arena

Smart pointers: unique_ptr, shared_ptr and weak_ptr

How C++ smart pointers own heap objects and free them automatically, and when to use each one.

Smart pointers own a heap object and delete it for you:

With smart pointers and containers, modern C++ code almost never calls new or delete directly.

Example

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

struct Enemy {
    std::string name;
    explicit Enemy(std::string n) : name(std::move(n)) {}
    ~Enemy() { std::cout << name << " removed\n"; }
};

int main() {
    auto boss = std::make_unique<Enemy>("Boss");
    std::unique_ptr<Enemy> owner = std::move(boss);
    std::cout << (boss == nullptr) << " " << owner->name << "\n";
    return 0;
}

Output:

1 Boss
Boss removed

Watch it run: unique_ptr owns and moves

Practice it