如果我不使用“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
关于c++ - 我应该如何释放不使用 "new"关键字创建的对象的内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59076229/