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

标签 c++ class memory dynamic struct

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

考虑这种情况:

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/

相关文章:

c++ - "cout"和 "char address"

c++ - 如何使用宏作为函数指针?

c++ - 不能对 long double 数据类型进行 openMP 矢量化操作吗?

java - 不兼容类型 : void cannot be converted to int

linux - 多线程进程的内存布局

python - 如何使用所有可用内存

c++ - fill_n() 不允许更改变量值

python - 字典中类内的函数

memory - glGenTextures 速度和内存问题

python - __init__ 方法中的异常处理