如何在不使用 "new" 关键字的情况下解除分配创建的对象的内存?

How should I deallocate the memory of an object created without using the "new" keyword?

本文关键字:情况下 解除分配 对象 内存 创建 new 关键字      更新时间:2023-10-16

如果我在不使用"new"关键字的情况下创建一个对象,我应该如何释放它的内存?

例:

#include "PixelPlane.h"
int main(void)
{
PixelPlane pixel_plane(960, 540, "TITLE");
//How should the memory of this object be freed?
}

pixel_plane是一个具有自动存储持续时间的变量(即普通局部变量(。

当封闭范围的执行结束时(即当函数返回时(,它将被释放。


这是没有自动存储持续时间的局部变量的示例。

void my_function()
{
static PixelPlane pixel_plane(960, 540, "TITLE");
// pixel_plane has static storage duration - it is not freed until the program exits.
// Also, it's only allocated once.
}

下面是一个不是函数的封闭范围的示例:

int main(void)
{
PixelPlane outer_pixel_plane(960, 540, "TITLE");
{
PixelPlane inner_pixel_plane(960, 540, "TITLE");
} // inner_pixel_plane freed here
// other code could go here before the end of the function
} // outer_pixel_plane freed here
相关文章: