有哪些一般提示可以确保我不会在C++程序中泄漏内存?我如何确定谁应该释放已动态分配的内存?
快速提问; 我已经用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; …Run Code Online (Sandbox Code Playgroud) 可能重复:
内存是否在C++中泄漏"未定义的行为"类问题?
从来没有调用delete或delete[]在C++程序中返回new或重新发送的地址new []是未定义的行为还是仅仅是内存泄漏?
欢迎参考标准(如果有的话).
这出现在这里的一条评论中,我对此感到有些困惑.
我问我的朋友,在被这个帖子吸引之后,他是否可以在不使用循环或编码的情况下从1到1000进行打印:
他用这个程序回答.
#include <iostream>
using namespace std;
static int n = 1;
class f {
public:
f() {
cout << n++ << endl;
}
};
int main(int argc, char *argv[]) {
f n [1000];
}
Run Code Online (Sandbox Code Playgroud)
运行程序输出正常.但是当我在netbeans上关闭程序时,它似乎仍在运行并消耗内存.该程序是否导致内存泄漏?有人可以解释这个小程序是如何工作的吗?