gpt4 book ai didi

C++ 释放结构使用的所有内存

转载 作者:IT王子 更新时间:2023-10-28 23:35:14 27 4
gpt4 key购买 nike

快速提问;我已经用谷歌搜索并找到了一些答案,但我有点偏执,所以我想确定一下。

考虑这种情况:

struct CoordLocation
{
float X;
float Y;
float Z;
};

int main()
{
CoordLocation *coord = new CoordLocation();
delete coord;
return 0;
}

调用 delete 是否也会清除字段 X、Y、Z 使用的内存?我发现的一些答案提到我只是删除 POINTER,而不是这种方式实际引用的对象。万一……

struct CoordLocation
{
float *X;
float *Y;
float *Z;
};

int main()
{
CoordLocation *coord = new CoordLocation();
delete coord;
return 0;
}

如果我手动释放结构的构造函数/析构函数中每个对象的内存呢?

struct CoordLocation
{
CoordLocation()
{
*X = new float;
*Y = new float;
*Z = new float;
}
~CoordLocation()
{
delete X; delete Y; delete Z;
}
float *X;
float *Y;
float *Z;
};

int main()
{
CoordLocation *coord = new CoordLocation();
delete coord;
return 0;
}

我注意到对于一个简单的情况,例如:

   float *a = new float;
*a = 5.0f;
printf("%f", *a);
delete a;
printf("%f", &a);

printf 将打印 5.0,因此 a 指向的变量并未完全销毁。

所以我的问题是:在这种情况下,如何可靠地释放(因为没有内存泄漏)结构使用的所有内存?

struct CoordLocation
{
float X;
float Y;
float Z;
};

int main()
{
CoordLocation *coord = new CoordLocation();
delete coord;
return 0;
}

谢谢!

最佳答案

您只需要delete您使用 new 分配的内存.

printf would print 5.0, so the variable pointed to by a is not exactly destroyed.

您实际上遇到了未定义的行为。虽然值还在,但是内存已经释放,可以重复使用了。

所以如下:

struct CoordLocation
{
float X;
float Y;
float Z;
};

如果省略析构函数,则不会造成内存泄漏。

你的下一个片段:

struct CoordLocation
{
float *X;
float *Y;
float *Z;
};

int main()
{
CoordLocation *coord = new CoordLocation();
delete coord;
return 0;
}

可能会造成内存泄漏,但并非如此。以下将:

int main()
{
CoordLocation *coord = new CoordLocation();
coord->X = new float();
delete coord;
return 0;
}

你的第三个例子

struct CoordLocation
{
CoordLocation()
{
*X = new float;
*Y = new float;
*Z = new float;
}
~CoordLocation()
{
delete X; delete Y; delete Z;
}
float *X;
float *Y;
float *Z;
};

int main()
{
CoordLocation *coord = new CoordLocation();
delete coord;
return 0;
}

不会造成内存泄漏,因为您释放了您分配的所有内存。如果您要省略析构函数或忘记调用 delete coord; ,他们就会有内存泄漏。

一个好的经验法则:调用 delete对于每个 newdelete[]对于每个 new[]你很安全。

关于C++ 释放结构使用的所有内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10252915/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com