new然后抛出C++构造函数?

uni*_*n83 5 c++ constructor throw new-operator

如果我做

Bat::Bat() : m_member_str(new std::string("Am I freed?"))
{
  throw std::runtime_error("oops");
}
Run Code Online (Sandbox Code Playgroud)

new分配的是免费的std::string吗?我在想它可能是因为没有调用析构函数.

我没有使用std :: string,而是使用我自己的类,只是将它显示为一个简单的例子.

thi*_*ton 3

这个例子是智能指针的经典用例。Bat未完全构造,因此不会调用析构函数,但m_member_str将调用 for 和所有其他完全构造的成员的析构函数。如果你不想要像 那样丑陋的块try { foo(); } catch (...) { delete m_member_str; },你就必须适应 RAII。

std::auto_ptrboost::scoped_ptr将在 C++03 或 C++11 中的等效项中为您提供帮助。将它们用于拥有的成员指针几乎没有什么缺点。