【发布时间】:2017-09-19 19:10:39
【问题描述】:
通常,您对不受限制的工会成员的生命周期负责 - 通常您通过就地 ctor/dtor 调用来做到这一点。但是,显然,至少在一种情况下编译器可以帮助你——在下面的代码中,如果对象构造失败,它(以前构造的)联合成员会自动销毁(至少在 MSVC 2015 中),即我们永远不会泄漏。
#include <string>
struct CanThrow
{
CanThrow() { throw 0; }
};
struct A
{
A() : str{} {} // note that we don't explicitly call str dtor here
~A() { str.~basic_string(); }
union { std::string str; };
CanThrow ct;
};
int main() { try{ A a; } catch(...) {} }
免责声明:此代码在我的 MSVC 2015 上编译
问题——这是由标准保证的吗?它在哪里规定?
【问题讨论】:
-
你怎么知道它被破坏了?
-
析构函数中的断点