【问题标题】:C++ Dynamic Memory // Destroying memory pointed by pointerC++ 动态内存 // 销毁指针指向的内存
【发布时间】:2021-02-28 14:44:51
【问题描述】:
#include <iostream>

using namespace std;

#define SELECT 0

class Z
{
    private:
        int *z1; int *z2;
    public:
        Z(const int x1 = 0, const int x2 = 0);
        Z(const Z &X);
        int *first (void) const {return z1;};
        int *second (void) const {return z2;};
        ~Z(void);
};

Z::Z(const int x1,const int x2){
    z1 = new int(x1);
    z2 = new int(x2);
}

#if SELECT == 1
Z::Z(const Z &X){
    z1 = new int(*X.first() );
    z2 = new int(*X.second() );
}
#else
Z::Z(const Z &X){
    z1 = X.first();
    z2 = X.second();
}
#endif

Z::~Z(){
    delete z1;
    delete z2;
}

int main()
{
 Z *zp;
    zp = new Z(3,5);
    Z  c(0,0);
    c = *zp;
    cout << "Content of c: " << *c.first() << " and " << *c.second() << endl;
    delete zp;
    cout << "Content of c: " << *c.first() << " and " << *c.second() << endl;
}

你好,当我运行这段代码时,我得到了类似的东西

Content of c: 3 and 5
Content of c: Garbage and Garbage

我期待这一点,因为我没有为 c 创建另一个内存,而是指向 zp 的内容。 但是,当我切换 #define SELECT 1 时,现在我正在为 c 创建新内存。所以当我删除 zp 时,c 仍然应该指向正确的值(存储在与 zp 不同的内存中)但我得到的仍然是下面显示的垃圾。

Content of c: 3 and 5
Content of c: Garbage and Garbage

问题出在哪里?

我还有一个问题。当我在 VScode 中调试它时,我得到“发生异常。未知信号”的行

    delete z1;
    delete z2;

在 CodeBlocks 中,没有错误。有什么问题?

感谢您的帮助。

【问题讨论】:

    标签: c++ pointers memory-management dynamic-memory-allocation


    【解决方案1】:

    你不遵守三个12的规则。

    复制构造函数只是三法则的一部分,但你还得实现复制赋值操作符。

    c = *zp; 不调用复制构造函数,而是调用复制赋值运算符,在您的情况下这是默认的,因为您没有指定任何内容。

    默认的复制赋值运算符将复制指针,因此在c = *zp; 之后,czpz1z2 具有相同的指针,这将导致双重释放(这肯定是你最后一个问题的原因)最初由zp分配的内存和由c分配的内存的内存泄漏。

    Z::Z(const Z &X){
        z1 = new int(*X.first() );
        z2 = new int(*X.second() );
    }
    
    Z& operator=(const Z& X)
    {
      *z1 = *(X.z1);
      *z2 = *(X.z2);
    
      return *this;
    }
    

    【讨论】:

      猜你喜欢
      • 2015-05-19
      • 1970-01-01
      • 1970-01-01
      • 2010-12-31
      • 1970-01-01
      • 2012-07-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多