Jav*_*son -3 c++ memory variables heap global
我有一个关于内存管理和全局变量与堆的问题,以及如何决定是否使用从堆分配空间而不是全局变量的变量。
我了解使用堆分配的变量会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)
使用堆或使用全局变量并不是真正的选择。实际上,如果可能,请勿使用以下任何一个:
#include <iostream>
int main()
{
int x = 5;
}
Run Code Online (Sandbox Code Playgroud)
没有明显的理由为什么x应该是全局的,也没有明显的理由使用手动内存分配,因此只使用具有自动存储功能的局部变量。