C ++动态内存//销毁指针指向的内存 [英] C++ Dynamic Memory // Destroying memory pointed by pointer
问题描述
#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;
}
你好,当我运行这段代码时,我得到类似
Hello, when I run this code, I get something like
Content of c: 3 and 5
Content of c: Garbage and Garbage
我一直期望如此,因为我没有为c创建另一个内存,而是指向zp的内容.但是,当我切换#define SELECT 1时,现在我正在为c创建新的内存.因此,当我删除zp时,c仍应指向正确的值(存储在与zp不同的内存中),但是我得到的仍然是下面显示的垃圾内容.
I was expecting this since, I am not creating another memory for c instead it points contents of zp. However, when I switch #define SELECT 1, now I am creating new memory for c. So when I delete zp, c still should point correct values (stored in different memory than zp) but what I get is still garbage shown below.
Content of c: 3 and 5
Content of c: Garbage and Garbage
问题出在哪里?
我还有一个问题.当我在VScode中调试此代码时,会出现发生异常".线路的信号未知
I have another question. When I debug this in VScode, I get "Exception Occured. Unknown signal "for the lines
delete z1;
delete z2;
在CodeBlocks中,没有错误.有什么问题吗?
In CodeBlocks, there is no error. What is the problem?
感谢您的帮助.
推荐答案
您没有遵循三个 2 .
You don't follow the rule of three 1 2.
复制构造函数只是这三个规则的一部分,但是您还必须实现复制赋值运算符.
The copy constructor is only one part of the rule of three, but you also have to implement the copy assignment operator.
c = * zp;
不会调用副本构造函数,而是调用副本赋值运算符,在您的情况下,这是默认值,因为您没有指定任何内容.
The c = *zp;
does not call the copy constructor but the copy assignment operator, which is in your case the default one because you didn't specify any.
默认的复制分配运算符将复制指针,因此在 c = * zp;
之后, c
和 zp
都具有相同的指针 z1
和 z2
会导致对 zp
和对于由 c
分配的内存,内存泄漏.
The default copy assignment operator will copy the pointers, so after c = *zp;
both c
and zp
have the same pointers for z1
and z2
which will lead to a double free (that's most certainly the reason for your last question) of the memory initially allocated by zp
and memory leaking for the memory allocated by 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;
}
这篇关于C ++动态内存//销毁指针指向的内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!