Search code examples
c++constructornew-operatorthrow

new then throw in C++ constructor?


If I do

Bat::Bat() : m_member_str(new std::string("Am I freed?"))
{
  throw std::runtime_error("oops");
}

Is the newly allocated std::string freed? I was thinking it might be because the destructor is not called.

I am not using a std::string, but my own class, just showing it as an easy example.


Solution

  • This example is the classic use case for smart pointers. Bat is not fully constructed, so the destructor won't be called, but the destructor for m_member_str and all other fully constructed members will be. If you don't want an ugly block like try { foo(); } catch (...) { delete m_member_str; }, you'll have to get comfortable with RAII.

    std::auto_ptr or boost::scoped_ptr will help you in C++03, or their equivalents in C++11. There is very little disadvantage in using them for owned member pointers.