gpt4 book ai didi

c++ - 析构函数异常时返回值的破坏

转载 作者:IT老高 更新时间:2023-10-28 12:31:21 26 4
gpt4 key购买 nike

我有以下代码:

#include <stdexcept>
#include <iostream>

struct ok {
int _n;
ok(int n) : _n(n) { std::cerr << "OK" << n << " born" << std::endl; }
~ok() { std::cerr << "OK" << _n << " gone" << std::endl; }
};

struct problematic {
~problematic() noexcept(false) { throw std::logic_error("d-tor exception"); }
};

ok boo() {
ok ok1{1};
problematic p;
ok ok2{2};
return ok{3}; // Only constructor is called...
}

int main(int argc, char **argv) {
try {boo();} catch(...) {}
}

我看到他没有调用ok{3}的析构函数,输出是:

 OK1 born
OK2 born
OK3 born
OK2 gone
OK1 gone

这是 C++14 的预期行为吗?

编辑:

使用 gcc 6.3 编译

最佳答案

根据标准,这种行为是错误的,问题的评论部分已经提到了这一点。这在关于 Exception handling 的部分中有说明。 .

根据 defect reportsopen-std.org ,他们早在 2015 年 9 月 28 日就已经意识到实现(GCC 和 Clang)在这方面是错误的。但提议的解决方案仅在 2016 年 2 月提出,编译器(GCC 和 Clang)尚未包含此修复程序。

Proposed resolution (February, 2016):

Change 18.2 [except.ctor] paragraph 2 as follows:
The destructor is invoked for each automatic object of class type constructed, but not yet destroyed, since the try block was entered. If an exception is thrown during the destruction of temporaries or local variables for a return statement (9.6.3 [stmt.return]), the destructor for the returned object (if any) is also invoked. The objects are destroyed in the reverse order of the completion of their construction. [Example:

  struct A { };

struct Y { ~Y() noexcept(false) { throw 0; } };

A f() {
try {
A a;
Y y;
A b;
return {}; // #1
} catch (...) {
}
return {}; // #2
}

At #1, the returned object of type A is constructed. Then, the local variable b is destroyed (9.6 [stmt.jump]). Next, the local variable y is destroyed, causing stack unwinding, resulting in the destruction of the returned object, followed by the destruction of the local variable a. Finally, the returned object is constructed again at #2. —end example]

GCC 中都针对此问题提交了错误。和 Clang .

对 GCC 错误报告的评论表明它显然是一个错误。

Jonathan Wakely评论:

It's now 2013 so the sensible thing to do is not return by value if your destructor can throw.

还有另一个用户:

Yes, I noticed, and Clang has also had a bug filed against them which has languished for years. Nevertheless, the behavior is wrong.

关于c++ - 析构函数异常时返回值的破坏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53167490/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com