【发布时间】:2020-08-02 11:09:33
【问题描述】:
我正在阅读C++17 standard draft 中第 18 节异常处理的第 18.2 节构造函数和析构函数,其中有一个示例(第 384 页)。我试图了解在 try 块内返回的对象 A 的破坏发生在哪里,但找不到。所以我复制了这个例子,添加了一些打印结果,发现该对象的 dtor 从未被调用过。我在这里想念什么?有人请解释一下这里发生了什么。
#include <stdio.h>
struct A {
int a_;
explicit A(int a):a_(a) {
printf("A(%d)'s ctor\n", a_);
}
~A() {
printf("A(%d)'s dtor\n", a_);
}
};
struct Y { ~Y() noexcept(false) {
printf("y's dtor\n");
throw 0; } };
A f() {
try {
A a(23);
Y y;
A b(56);
return A(100); // #1 who destructs this ??
} catch (...) {
printf("handling exception..\n");
}
printf("At line %d now..\n", __LINE__);
return A(200); // #2
}
int main() {
auto ret = f();
printf("f returned A(%d) object\n", ret.a_);
return 0;
}
以上代码输出如下:
A(23)'s ctor
A(56)'s ctor
A(100)'s ctor
A(56)'s dtor
y's dtor
A(23)'s dtor
handling exception..
At line 34 now..
A(200)'s ctor
f returned A(200) object
A(200)'s dtor
...Program finished with exit code 0
【问题讨论】:
-
你已经演示了为什么析构函数永远不能安全地抛出异常。
-
您链接的文档是 C++17 后的草案(请参阅 N4659 了解 C++17 标准)
-
@ChrisDodd 不是,这个程序是为了定义明确的
-
问题在于,在析构函数上允许任何异常的任何异常规范都无法安全地实现,因为在该帧完全销毁之前退出该帧时可能会引发异常。
-
@ChrisDodd 标准没有提到“框架”
标签: c++ exception return-value destructor throw