【问题标题】:How should I deallocate the memory of an object created without using the "new" keyword?我应该如何释放不使用“new”关键字创建的对象的内存?
【发布时间】:2020-03-23 08:46: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 的生命周期结束时自动发生,当范围结束时发生。这会导致对象破坏和内存被释放(以实现定义的方式)。
  • 如果对象有适当的析构函数,则不需要。见:stackoverflow.com/questions/4036394/…
  • 为什么要投反对票?问题已正确提出。你不应该仅仅因为你知道答案就投票给人们,他们不知道,而且你认为这是基本的。 每个 C++ 的学生都需要学习这个问题的答案,所以它对很多人来说都是有用的信息。
  • @SuperSim135 是的,当进程终止时。
  • 方便阅读:Storage class specifiers 所有这些都是信息性的,但是关于存储持续时间的部分是最相关的。

标签: c++ oop memory-management


【解决方案1】:

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

【讨论】:

  • 在相关块的执行结束时释放存储空间,而不是在作用域结束时释放。范围没有任何时间的结束,只是到位。范围是 where 在源代码标识符可见。存储持续时间或生命周期是在程序执行对象存在期间。自动对象在其关联块的执行结束时不复存在(而不仅仅是在程序控制暂时离开该块时,如调用子程序时)。
猜你喜欢
  • 2012-03-07
  • 1970-01-01
  • 2018-06-07
  • 2016-03-18
  • 1970-01-01
  • 1970-01-01
  • 2023-03-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多