以下代码为 g++ 版本 4.6.2 提供了一个异常(exception),但在 g++ 版本 4.2.1 中按预期运行。执行期间打印的消息表明,在这两种情况下,都会在从未构造过的地址上调用析构函数。我想知道(a)哪个编译器是正确的,(b)为什么有些东西没有被创造就被破坏了。非常感谢。
//------------------------------------------------------
#include <iostream>
using namespace std;
class Poly{
private:
float *coeff;
public:
Poly(){
coeff = NULL;
cout << "Created "<< this << endl;
}
Poly(Poly const & p){ // copy constructor
coeff = NULL;
cout << "Executed copy constructor.\n";
}
Poly operator=(Poly const & rhs){
cout << "Executed assignment. " << this << " = " << &rhs << endl;
}
Poly fun(){
Poly c;
return c;
}
~Poly(){
cout << "Destructor: " << this << endl;
delete[] coeff;
}
};
main(){
Poly a;
a = a.fun();
}
//------------------------------------------------------
对于 g++ 4.6.2,它给出了异常:
% ./a.out
Created 0xbfdcc184
Created 0xbfdcc18c
Executed assignment. 0xbfdcc184 = 0xbfdcc18c
Destructor: 0xbfdcc188
*** glibc detected *** free(): invalid pointer: 0xbfdcc1a8 ***
Aborted
对于 g++ 4.2.1,它执行以下操作
% ./a.out
Created 0x7fff5fbff930
Created 0x7fff5fbff920
Executed assignment. 0x7fff5fbff930 = 0x7fff5fbff920
Destructor: 0x7fff5fbff910
Destructor: 0x7fff5fbff920
Destructor: 0x7fff5fbff930
没有异常(exception),代码越多,它就会产生正确的答案。但是,它似乎确实在破坏从未构建过的 0x7fff5bff910。请注意,永远不会调用复制构造函数,如果调用过,它会打印一条消息。
最佳答案
看起来你的“Poly operator=”没有返回任何东西。
关于c++ - 在未构造的对象上调用析构函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9348684/