如果我有一个function声明一个int,最后function我需要"释放" int以节省内存?
例:
void doSomething() {
int x = 0;
// do something with x
free(x); // needed?
}
Run Code Online (Sandbox Code Playgroud)
这是你的记忆管理诫命
正如其他人所提到的,不,您不需要专门释放内存,因为变量在函数末尾超出了范围。
然而,稍微不同的是,我在寻找一种快速、干净地释放原始变量内存的方法时遇到了这个页面,后来发现了一种令人难以置信的方法来做到这一点,我没有意识到这是 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)
| 归档时间: |
|
| 查看次数: |
2973 次 |
| 最近记录: |