Sahaj.blogs
5 Jan 2024 · StudyPhase 2 · C++

C++ · Memory: new, delete and RAII

Stack vs heap, manual new/delete and why it leaks, and RAII: tying a resource's lifetime to an object's scope.

Python has a garbage collector. C++ gives you two places to put objects:

  • Stack: local variables. They’re created when declared and destroyed automatically at the end of the scope.
  • Heap: new T allocates memory that lives until delete. If you forget delete, it leaks. If you delete twice, or use the memory after deleting, that’s undefined behaviour.

RAII (Resource Acquisition Is Initialisation) is the C++ answer: wrap the resource in an object that acquires it in its constructor and releases it in its destructor. Because destructors always run when scope ends, even when an exception is thrown, cleanup can’t be forgotten. std::vector, std::string, file streams and smart pointers all work this way.

#include <iostream>
#include <stdexcept>

struct Tracker {
    const char* name;
    explicit Tracker(const char* n) : name(n) { std::cout << "  acquire " << name << '\n'; }
    ~Tracker() { std::cout << "  release " << name << '\n'; }
};

void risky() {
    Tracker t("raii-guard");
    throw std::runtime_error("something failed");
}   // t is released even though we throw

int main() {
    std::cout << "manual heap:\n";
    Tracker* p = new Tracker("heap-object");
    delete p;                          // forget this and it leaks

    std::cout << "stack scope:\n";
    { Tracker s("stack-object"); }

    std::cout << "exception:\n";
    try { risky(); }
    catch (const std::exception& e) { std::cout << "  caught: " << e.what() << '\n'; }
}

Output:

manual heap:
  acquire heap-object
  release heap-object
stack scope:
  acquire stack-object
  release stack-object
exception:
  acquire raii-guard
  release raii-guard
  caught: something failed

#cpp#memory

Sources

  1. new expression — cppreference.com
  2. RAII — cppreference.com
  3. C++ Core Guidelines R.1: manage resources automatically using RAII — Standard C++ Foundation