下面的代码给出了g ++版本4.6.2的一个例外,但是按照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
没有例外,并用更多的代码它确实会产生正确的答案。但是,它似乎破坏了从未构建过的0x7fff5bff910。请注意,复制构造函数永远不会被调用,它会打印出一条消息。
您可以确保您发布了您正在使用的确切代码。没有返回类型的'main'应该会产生一个编译错误。 – 2012-02-19 11:50:08
...对于那些认为在NULL上调用'delete []'是错误的人:**“在任何一种替代[delete和delete []]中,如果delete的操作数的值是空指针,则操作没有任何效果。“** – LihO 2012-02-19 12:01:18