析构函数被调用在未构造的东西上

Eka*_*vya 4 c++ destructor

以下代码为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();
}
//------------------------------------------------------
Run Code Online (Sandbox Code Playgroud)

对于g ++ 4.6.2,它给出了异常:

% ./a.out
Created 0xbfdcc184
Created 0xbfdcc18c
Executed assignment. 0xbfdcc184 = 0xbfdcc18c
Destructor: 0xbfdcc188
*** glibc detected *** free(): invalid pointer: 0xbfdcc1a8 ***
Aborted
Run Code Online (Sandbox Code Playgroud)

对于g ++ 4.2.1,它执行以下操作

% ./a.out
Created 0x7fff5fbff930
Created 0x7fff5fbff920
Executed assignment. 0x7fff5fbff930 = 0x7fff5fbff920
Destructor: 0x7fff5fbff910
Destructor: 0x7fff5fbff920
Destructor: 0x7fff5fbff930
Run Code Online (Sandbox Code Playgroud)

没有例外,并且通过更多代码,它确实产生了正确的答案.但是,它似乎正在破坏从未构建过的0x7fff5bff910.请注意,永远不会调用复制构造函数,如果存在,它将打印一条消息.

inn*_*nti 6

看起来你的"Poly operator ="没有返回任何内容.