Seb*_*che 7 c++ destructor c++builder
以下代码演示了Turbo C++ Explorer项目中的一个奇怪问题.超出范围后,D :: D()中的三个堆栈对象之一不会被销毁.
只有在发布模式下编译时才会发生这种情况,auto_ptrs a_和b_属于不同类型,抛出的异常不会从std :: exception继承.它似乎在VC++ 2005和C++ Builder 2009中工作正常.我确实安装了BDS2006 Update 2,修补程序汇总和修补程序12.
是我的代码还是编译器?你知道修复吗?无法在VCL项目中可靠地使用auto_ptr会非常不方便.
#include <memory>
#include <stdexcept>
#include <iostream>
typedef std::exception my_error; // will work fine if replaced with line below
//class my_error : public std::exception {};
class A {};
class B {};
class C
{
public:
C(int id) : id_(id) { std::cout << "C::C() " << id_ << std::endl; };
~C() { std::cout << "C::~C() " << id_ << std::endl; };
private:
int id_;
};
class D
{
public:
D()
{
C c1(1);
C c2(2);
C c3(3);
throw my_error();
};
private:
std::auto_ptr<A> a_;
std::auto_ptr<B> b_; // will work fine if replaced with line below
// std::auto_ptr<A> b_;
// std::auto_ptr<C> c_; // see expected output
};
#pragma argsused
int main(int argc, char* argv[])
{
try
{
D d;
}
catch (...)
{
std::cout << "caught exception" << std::endl;
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
预期:
C::C() 1 C::C() 2 C::C() 3 C::~C() 3 C::~C() 2 C::~C() 1 caught exception
拿到:
C::C() 1 C::C() 2 C::C() 3 C::~C() 2 C::~C() 1 caught exception
得到(行' // std::auto_ptr<C> c_;
'未注释):
C::C() 1 C::C() 2 C::C() 3 C::~C() 1 caught exception
编辑:提出建议的更改
编辑2:
我刚用C++ Builder 2007(11.0.2902.10471)测试它,它显示了同样的问题.检查项目 - >选项 - > C++编译器 - >调试中的"调试信息"框后,发布配置就会起作用.让我感到惊讶的是,在启用"调试信息"的情况下,可执行文件变得更小(从39.5 KB减少到31.5 KB).
编辑3:
在Turbo C++ Explorer(C++ Builder 2006)(10.0.2288.42451)中,如果取消选中Project - > Options - > C++ Compiler - > Debugging中的"Inline function expansion(-vi)"框,则发布配置有效.#include <memory>
用以下代码替换第一行()也可以使用它.
#pragma option push -vi-
#include <memory>
#pragma option pop
Run Code Online (Sandbox Code Playgroud)