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:
std::unique_ptr<T>: exactly one owner. Can't be copied, only moved. Zero overhead. The default choice. Make one withstd::make_unique<T>(args).std::shared_ptr<T>: shared ownership with a reference count; the last owner deletes it. Use only when ownership is genuinely shared.std::weak_ptr<T>: watches a shared object without keeping it alive, to break reference cycles.
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