Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 914
unixman83 Avatar asked Dec 28 '11 11:12

unixman83


1 Answers

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.

like image 119
thiton Avatar answered Nov 15 '22 12:11

thiton