我有一个关于内存管理和全局变量与堆的问题,以及如何决定是否使用从堆分配空间而不是全局变量的变量。
我了解使用堆分配的变量会new在程序的整个生命周期内持续使用,而全局变量也会在程序的生命周期内持续使用。
应该使用堆变量而不是全局变量吗?
以下面这两种方法为例,就代码速度和内存管理而言,这是更合适的,为什么该方法更合适:
#include <iostream>
int x = 5;
int main(int argc, char** argv)
{
// do stuff with the variable x
return 0;
}
Run Code Online (Sandbox Code Playgroud)
与
#include <iostream>
int main(int argc, char** argv)
{
int x = new int;
*x = 5;
// do stuff with the variable pointed to by x
delete x;
return 0;
}
Run Code Online (Sandbox Code Playgroud)