C++C++
IntermediateLesson 11 of 18

RAII and Smart Pointers – C++

Managing resources safely with unique_ptr, shared_ptr and weak_ptr – without new and delete.

RAII (Resource Acquisition Is Initialization) is the heart of modern C++: a resource (memory, file, mutex) is acquired in the constructor and released in the destructor. This way there are no leaks – even with exceptions or an early return.

Smart pointers apply this to heap memory. std::unique_ptr has exactly one owner, is not copyable but movable, and costs nothing extra:

#include <iostream>
#include <memory>

struct Ding {
    Ding()  { std::cout << "Thing created\n"; }
    ~Ding() { std::cout << "Thing destroyed\n"; }
    void hallo() const { std::cout << "hello\n"; }
};

int main() {
    auto p = std::make_unique<Ding>();
    p->hallo();
    auto q = std::move(p);                  // transfer ownership
    std::cout << (p ? "p owns" : "p is empty") << '\n';
}   // output: Thing created, hello, p is empty, Thing destroyed

std::shared_ptr shares the object via a reference counter: the object is destroyed when the last owner disappears. std::weak_ptr observes without counting – important against cycles.

#include <iostream>
#include <memory>

int main() {
    auto a = std::make_shared<int>(42);
    {
        auto b = a;                                    // second owner
        std::cout << a.use_count() << '\n';            // 2
    }
    std::cout << a.use_count() << '\n';                // 1

    std::weak_ptr<int> w = a;
    if (auto s = w.lock()) std::cout << *s << '\n';    // 42
    a.reset();                                         // last owner gone
    std::cout << std::boolalpha << w.expired() << '\n';   // true
}
  • Default: unique_ptr (std::make_unique<T>(...))
  • shared_ptr only when ownership is genuinely shared (std::make_shared)
  • Raw pointers and references only as a non-owning view
  • Avoid new/delete/malloc in application code
  • Write your own RAII classes for files, locks, connections (std::lock_guard, std::fstream set the example)
WarningTwo shared_ptrs that own each other never free (memory leak). One part of the relationship should be modeled as a weak_ptr. Never create two independent smart pointers from the same raw pointer.