8 c++ memory struct class dynamic
快速提问; 我已经用Google搜索并找到了一些答案,但我有点偏执,所以我想确定一下.
考虑这种情况:
struct CoordLocation
{
float X;
float Y;
float Z;
};
int main()
{
CoordLocation *coord = new CoordLocation();
delete coord;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
调用delete还会清除X,Y,Z字段使用的内存吗?我发现的一些答案提到我只是删除了POINTER,而不是这种方式实际引用的对象.如果...
struct CoordLocation
{
float *X;
float *Y;
float *Z;
};
int main()
{
CoordLocation *coord = new CoordLocation();
delete coord;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
如果我为struct的构造函数/析构函数中的每个对象手动释放内存怎么办?
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;
}
Run Code Online (Sandbox Code Playgroud)
我注意到一个简单的情况,例如:
float *a = new float;
*a = 5.0f;
printf("%f", *a);
delete a;
printf("%f", &a);
Run Code Online (Sandbox Code Playgroud)
printf将打印5.0,因此a指向的变量并未完全销毁.
所以我的问题是:在这种情况下,如何可靠地释放(因为没有内存泄漏)结构使用的所有内存?
struct CoordLocation
{
float X;
float Y;
float Z;
};
int main()
{
CoordLocation *coord = new CoordLocation();
delete coord;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
谢谢!
Luc*_*ore 19
你只需要delete分配的内存new.
printf将打印5.0,因此a指向的变量并未完全销毁.
你实际上遇到了未定义的行为.虽然值仍然存在,但内存已释放并可以重复使用.
所以以下内容:
struct CoordLocation
{
float X;
float Y;
float Z;
};
Run Code Online (Sandbox Code Playgroud)
如果省略析构函数,则无法创建内存泄漏.
你的下一个片段:
struct CoordLocation
{
float *X;
float *Y;
float *Z;
};
int main()
{
CoordLocation *coord = new CoordLocation();
delete coord;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
可能会造成内存泄漏,但不是原样.以下将:
int main()
{
CoordLocation *coord = new CoordLocation();
coord->X = new float();
delete coord;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
你的第三个例子
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;
}
Run Code Online (Sandbox Code Playgroud)
不会创建内存泄漏,因为您释放了所分配的所有内存.如果你要省略析构函数或忘记调用delete coord;,那么你就会发生内存泄漏.
一个好的经验法则:调用delete每一个new和delete[]每一个new[]与你的安全.
| 归档时间: |
|
| 查看次数: |
20632 次 |
| 最近记录: |