如果我在不使用“ 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
TL; DR:分别考虑在PixelPlane
的构造函数和析构函数中获取和释放内存。
该成语称为RAII。这个想法是-考虑到值语义(即直接处理对象而不是引用),对象析构函数总是在超出范围时被调用。您可以利用此功能释放要破坏的对象拥有的任何资源。
因为它在破坏时释放了资源,所以在构造时(即在其构造函数中)获取它确实有意义。
自C ++ 11起,您可以使用移动语义来转移对象拥有的资源的所有权。