Skip to content
UPEEC

Smart Pointers

unique_ptr and shared_ptr manage heap memory automatically — no manual delete.

Intermediate
Comments 0
#include <memory>

auto sensor = std::make_unique<Dht22>();       // sole owner, freed automatically
auto config = std::make_shared<Config>();      // reference-counted shared owner
std::weak_ptr<Config> watcher = config;        // observes without owning
  • unique_ptr — one owner, zero overhead, can be moved but not copied.
  • shared_ptr — many owners; freed when the last one goes away.
  • weak_ptr — breaks reference cycles.

Modern C++ rarely uses raw new and delete.

Spotted a mistake or want to add detail? Suggest an improvement — Content Contributors' edits are reviewed by editors before they go live.

Discussion (0)

Sign in or join free to ask questions and discuss this topic.