How do I deal with memory leaks? (2022)

· coding · Source ↗

Bjarne Stroustrup’s C++ Style and Technique FAQ, last touched February 2022, answers memory leaks with a single imperative: use RAII containers like std::vector and let destructors do the work.

What Matters

  • Stroustrup’s core answer to memory leaks: reduce explicitly managed objects from “tens of thousands to a few dozens” via abstractions.
  • std::vector is the canonical example — it allocates on demand and frees on scope exit; no explicit delete required.
  • The FAQ recommends the C++ Core Guidelines as the living coding standard, replacing all pre-2010 C++ or C-derived standards.
  • Protected base-class data members are flagged as a structural mistake: they couple user code to implementation details and force recompilation on changes.
  • auto_ptr appears in the FAQ despite being deprecated in C++11 and removed in C++17 — the page shows its age.
  • [HN: @eska] std::sort(), auto_ptr, and RAII coexist on the page — a combination that was always broken given auto_ptr‘s broken copy semantics.
  • [HN: @shmolyneaux] The FAQ’s own sample code uses typedef mid-function and .begin()/.end() everywhere, raising questions about whether Stroustrup’s idioms reflect current best practice.

Original | Discuss on HN