Pointers, RAII & Smart Pointers

Raw pointers, new/delete, RAII, unique_ptr, shared_ptr and weak_ptr.

Beginner
Key PointsRAII ties resource lifetime to scope; modern C++ uses smart pointers, not new/delete.
C++
#include <memory>
#include <iostream>

void use() {
    auto up = std::make_unique<int>(10);   // exclusive ownership
    auto sp = std::make_shared<int>(20);   // refcounted ownership
    std::weak_ptr<int> wp = sp;            // break cycles
    std::cout << *up << ' ' << *sp << '\n';
}  // freed automatically
shared_ptr cycles leak; store weak_ptr for back-references (e.g. parent links).

Friends & Partners