title: C++ memory management paradigms
body: <p>I'm moving from C to C++11 and trying to figure out the memory management paradigm for C++11 programs (or any modern languages with built-in exceptions). Specifically, I'm having a crack at game development where running out of memory is a real concern.</p>
  
  <p>In C, I'm using to checking the return value of malloc; and generally use custom allocators.</p>
  
  <p>With C++, I'm quite confused; though I like how the STL containers were built allowing custom allocators. Since the STL containers all manage their own memory, simply adding an element to a vector could throw a <code>std::bad_alloc</code>. How do I guard against such things? I have heard wrapping all throwing calls in try/catch blocks can be prohibitively expensive. </p>
  
  <p>However, allowing the exception to travel up the callstack would allow in a bunch of functions that would not fully execute, and would lead to some really tricky code. i.e. if <code>A-&gt;B-&gt;C-&gt;D</code> is a callstack, <code>D</code> throws, and <code>A</code> catches, then <code>B</code>, <code>C</code>, and <code>D</code> could have potentially created some weird problems by not being able to finish execution normally.</p>
  
  <p>Additionally, the <code>nothrow</code> argument seems to allow very C-like code; though I now don't see the benefit over a plain malloc.</p>
  
  <p>What are some best practices out there for writing exception-safe C++ code that guards against out-of-memory issues?</p>
  
  <p><strong>edit:</strong> <a href="https://softwareengineering.stackexchange.com/a/113481">A relevant answer on progammers.stackexchange arguing for exception-less C++ design in consoles.</a> Not sure if these arguments still apply to the <a href="http://en.wikipedia.org/wiki/History_of_video_game_consoles_(eighth_generation)" rel="nofollow noreferrer">8th generation consoles</a></p>