那么我们会得到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;
}
对于 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
http://coliru.stacked-crooked.com/a/9658b14c73253700
如果块作用域变量在初始化期间抛出异常,那么我们是否会得到未定义行为?