C++ Programming Best Practices in Scientific Computing

This is a presentation by Alfredo Correa (LLNL) on good C++ programming practices.  C++ techniques from AFQMC.pdf. Alfredo is supported in part by the QMCPACK ECP project, which also supports Nichols A. Romero (Unlicensed).

(Reproducing two of the main slides)

When is a good idea to use OO (virtual, new,>, etc)? (spoiler: almost never to do math or a simulation)

Perhaps if:

  • Immutable (but polymorphic) state
  • Shared/singleton objects/representations of logic
  • `In-the-heap-anyway'
  • Open hierarchies (e.g. open behavior, cross compilation-boundaries)
  • Exceptions (std::runtime_error)
  • Resources (std::pmr::memory_resource)
  • Devices (std::iostream)

Perhaps not if:

  • - - - Value Semantics
  • Mutability
  • Local reasoning

Remember, virtual was never used in the STL and it still went a long way:

$ grep -R virtual /usr/include/c++/*


  • Try not to add new virtual functions
  • Give your arithmetic types value semantics
  • Use constructors and assignment instead of (pointer-) factories
  • (make * functions are ok)
  • OO can coexists with Generic Programming and slowly fade away
  • Use the stack for objects, or be stack-friendly
  • Use dynamic memory as an internal implementation detail
  • Use algorithms (100+ STL algorithms)\
  • (chances are your loops are in essence existing algorithms)
  • Use containers, even custom containers/iterators/pointers
  • Use dynamic memory generically through allocators