小编Jav*_*son的帖子

如何决定应该使用全局变量还是应该使用堆?

我有一个关于内存管理和全局变量与堆的问题,以及如何决定是否使用从堆分配空间而不是全局变量的变量。

我了解使用堆分配的变量会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)

c++ memory variables heap global

-3
推荐指数
1
解决办法
123
查看次数

标签 统计

c++ ×1

global ×1

heap ×1

memory ×1

variables ×1