Skip to content

RAII Memory Management

williamfgc edited this page May 4, 2017 · 2 revisions
  1. Avoid new/delete bare pointers: use objects, references to objects, smart pointers: unique_ptr, shared_ptr, and the standard template library (STL) containers (e.g. std::vector, std::map, std::queue ) when corresponding for automatic memory management. In addition, use smart pointers for polymorphism and/or to allow nullptr as a valid state (e.g. waiting for message). Only use bare pointers as "reference" pointers, not to manage memory manually.

    • Don't
      double *variable = new double [Nx];
    • Do
      std::vector<double> variable(Nx);
      
  2. std::move and C++11: C++11 adds overloaded standard functions and constructors that automatically identify an object's move constructor (&&) (e.g. STL containers element insertion, deletion). Only use std::move explicitly when it is not clear if the copy (&) or move (&&) constructor will be called (e.g. large user-defined objects moved to a container, in that case prefer emplace_back).

  3. Use RAII: resource allocation is initialization. Constructors must allocate, while destructors will take care of all object deallocations and system resources (e.g. file, shared memory). Fine tuning memory should be used only if it causes a big impact. STL containers and smart pointers are RAII complaint. If a class only contains RAII members destructors should be empty or declared with the keyword default.