在cpp中,我是否必须始终"释放"原始变量?

Tom*_*ito 2 c++

如果我有一个function声明一个int,最后function我需要"释放" int以节省内存?

例:

void doSomething() {
    int x = 0;
    // do something with x
    free(x); // needed?
}
Run Code Online (Sandbox Code Playgroud)

Arm*_*yan 7

这是你的记忆管理诫命

  • 汝等免费只是将你所malloc分配calloc'ed
  • 你只能删除所做的新事物
  • 你只删除[]新的[]'ed
  • 你应尽可能使用RAII

  • 还有:"你不能在C++中使用free和malloc/calloc" (6认同)
  • 这是什么英语? (3认同)

unw*_*ind 5

不。它是一个自动变量,这意味着它在超出范围时会被释放。

此外,您很少free()在 C++ 中使用,它是一个 C 函数。


Nic*_*ton 5

正如其他人所提到的,不,您不需要专门释放内存,因为变量在函数末尾超出了范围。

然而,稍微不同的是,我在寻找一种快速、干净地释放原始变量内存的方法时遇到了这个页面,后来发现了一种令人难以置信的方法来做到这一点,我没有意识到这是 C++ 的一部分。对于其他也在寻找这个答案的人来说,它就在这里。

实际上,您可以使用额外的大括号来设置 C++ 中变量的特定范围,因此在该函数中释放“x”的内存而无需函数结束的一种方法是将“x”的范围包含在像这样的大括号:

void doSomething() {
    // do something in the start of the function
    {

        int x = 0;
        // do something with x

    } // x is destroyed here

    // do something that doesn't require x
}
Run Code Online (Sandbox Code Playgroud)