【发布时间】:2016-01-26 19:05:08
【问题描述】:
下面的代码使得析构函数被调用两次。
#include <iostream>
#include <memory>
#include <exception>
#include <cstdlib>
void myterminate()
{
std::cout << "terminate\n";
abort();
}
class data
{
int a;
public:
data(int a) : a(a) { std::cout << "ctor " << a << "\n"; }
~data() { std::cout << "dtor " << a << "\n"; }
static data failure(int a) { return data(a); }
};
void main()
{
std::set_terminate(myterminate); //terminate is not called
try
{
std::unique_ptr<data> u;
u.reset(&data::failure(1));
std::cout << "no worries\n"; //this prints
//destructor called at try-block end and attempt to destruct an invalid memory block.
}
catch (...)
{
std::cout << "caught\n"; //this can not catch the error
}
std::cout << "end\n"; //program crash, will not be called
}
如何在生产中发现这样的错误?
【问题讨论】:
-
C++ - 应该是
int main -
我不确定它是否由语言指定,两次删除对象是未定义的行为,std::set_terminate 没有义务响应未定义的行为。
-
您的代码具有未定义的行为,因此在运行时“捕获”错误将毫无意义。你需要修复这个错误。
-
为什么不按“Wiederholen”进行调试?
-
你不。您确保在测试中发现它,然后在代码投入生产之前对其进行修复。好的单元测试应该能够捕捉到这一点。
标签: c++ c++11 unique-ptr terminate-handler