c++ - 我应该如何释放不使用 "new"关键字创建的对象的内存?

标签 c++ oop memory-management

如果我不使用“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/

相关文章:

c++ - std::deque 内存使用

php - 从字符串中删除多余的引号

javascript - 如何从构造函数调用对象的方法?

C# 内存使用过多

c++ - C 和 C++ : Freeing PART of an allocated pointer

c# - 如何在 C# 中尽可能快地填充内存

c# - 在窗口出现之前拦截并隐藏它

c++ - 为什么 cin 会导致该程序挂起?

java - “使用静态数组”...这是什么意思?

c++ - 从 `std::vector<char>` 内部的位获取整数