相关疑难解决方法(0)

避免C++内存泄漏的一般准则

有哪些一般提示可以确保我不会在C++程序中泄漏内存?我如何确定谁应该释放已动态分配的内存?

c++ memory memory-management raii

127
推荐指数
10
解决办法
12万
查看次数

C++释放struct使用的所有内存

快速提问; 我已经用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++ memory struct class dynamic

8
推荐指数
1
解决办法
2万
查看次数

没有delete()的new()是Undefined Behavior还是仅仅是Memory Leak?

可能重复:
内存是否在C++中泄漏"未定义的行为"类问题?

从来没有调用deletedelete[]在C++程序中返回new或重新发送的地址new []是未定义的行为还是仅仅是内存泄漏?

欢迎参考标准(如果有的话).
这出现在这里的一条评论中,我对此感到有些困惑.

c++ memory-leaks new-operator undefined-behavior

1
推荐指数
2
解决办法
3216
查看次数

该程序是否会导致内存泄漏

我问我的朋友,在被这个帖子吸引之后,他是否可以在不使用循环或编码的情况下从1到1000进行打印:

在没有循环或条件的情况下打印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上关闭程序时,它似乎仍在运行并消耗内存.该程序是否导致内存泄漏?有人可以解释这个小程序是如何工作的吗?

c++ memory-leaks

0
推荐指数
1
解决办法
258
查看次数