c++ - 在未构造的对象上调用析构函数

标签 c++ destructor

以下代码为 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/

相关文章:

c++ - NormalTexture 在 Wavefront 资源 Material 格式中如何表示?

c++ - 有什么方法可以将 3rd 方 DLL 中的静态变量重置为其原始值吗?

c++ - 找不到n * n矩阵的行列式

c++ - 销毁返回对象

c++ - 不销毁作为 union 成员的类类型的对象是否安全?

c++ - 如何释放数组的单个元素?

c++ - 一张一张打开箱顶

C++删除继承类

c++ - 为什么构造函数/析构函数被调用一次?

c++ - 在程序结尾处在0x0037A5C2 project.exe上引发了异常:0xC0000005:访问冲突写入位置0xDDDDDDDD