我在想:他们说如果你手动调用析构函数 - 你做错了什么.但情况总是这样吗?有反例吗?有必要手动调用它或者难以避免的情况/不可能/不切实际的情况吗?
那我们会得到UB吗?我试过这个:
#include <iostream>
struct B
{
B(){ std::cout << "B()" << std::endl; }
~B(){ std::cout << "~B()" << std::endl; }
};
struct A
{
B b;
A(){ std::cout << "A()" << std::endl; throw std::exception(); }
~A(){ std::cout << "~A()" << std::endl; }
};
int main()
{
A a;
}
Run Code Online (Sandbox Code Playgroud)
desctructor没有被要求netither A也没有B.实际输出:
B()
A()
terminate called after throwing an instance of 'std::exception'
what(): std::exception
bash: line 7: 21835 Aborted (core dumped) ./a.out
Run Code Online (Sandbox Code Playgroud)
http://coliru.stacked-crooked.com/a/9658b14c73253700
因此,在块范围变量初始化期间构造函数抛出的任何时候,我们都得到UB吗?