【发布时间】:2019-04-09 14:03:27
【问题描述】:
我有以下代码:
#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 编译
【问题讨论】:
-
编译器和版本? cl v19.16.26926 不会发生
-
我认为您应该将
language-laywer标签添加到问题中,并对其进行编辑以询问它在标准中是如何定义的。当然,包括您正在使用的确切编译器(和版本)。可能添加您的构建方式(使用优化标志等)。 -
"如果局部变量的析构函数或 return 语句中使用的临时变量的析构函数抛出异常,则函数返回的对象的析构函数也会被调用。(自 C ++14)" en.cppreference.com/w/cpp/language/throw
-
这是defect #2176。该修复程序可能尚未进入 6.3。
标签: c++ exception c++14 destructor object-lifetime