【发布时间】: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