New and then throw in a C ++ constructor?

If i do

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

Is newly highlighted highlighted std::string? I thought it could be because the destructor is not called.

I do not use std :: string , but my own class, just showing it as a simple example.

+5
source share
4 answers

This example is a classic use case for smart pointers. Batnot completely constructed, so the destructor will not be called, but the destructor for m_member_strand all other fully constructed elements will be. If you don’t need an ugly block, for example try { foo(); } catch (...) { delete m_member_str; }, you will need to enjoy RAII.

std::auto_ptr boost::scoped_ptr ++ 03 ++ 11. .

+3

. .

Bat , . ~Bat() .

m_member_str, , , . .

std::string*, . , , .

, , .

, RAII , , .

, , , , bny, , , .

+3

, , . - -. , , m_member_str, , .

+1

- !;-P

?

, ,

. , , , ( try/catch ).

m_member_str, -?

(-, , - m_member_str , , - .)

If you must have a pointer, use a smart pointer to capture the pointer so that the smart pointer destructor destroys the object with the pointer and frees memory. This will be triggered because a failed constructor destroys already constructed member variables during exception handling.

+1
source

All Articles