如何在C++中删除变量

Tom*_*oni 3 c++ types visual-studio visual-c++

我想在我的程序中释放ram.

即使我是新手,我也非常关心性能.

string i_want_to_delete_this = "I don't want this cleared, but            
completely gone";
/* I figured out */ i_want_to_delete_this.clear() /* simply sets the
string value to "". I want to be able to do this with every
datatype! I want it completely gone, not even declared anymore. */
Run Code Online (Sandbox Code Playgroud)

小智 8

我不明白你为什么要这样做,并且在任何情况下你都不能删除或以其他方式删除命名变量,除非它们在概念上被编译器在超出范围时被你删除,并且实际上被删除了包含它们的函数退出.例如:

{
   {
       string i_want_to_delete_this = "I don't want this cleared, but            
completely gone";
   }     // it's gone
}
Run Code Online (Sandbox Code Playgroud)


Cyg*_*sX1 8

有3种变量。根据您管理内存的类型不同。

全局变量

它们位于程序的特殊部分。它们在程序启动时出现,在程序结束时消失。您无法执行任何操作来回收全局变量占用的内存。一些更复杂的常量也可能属于这一类。无论您是否将其复制到变量,您的字符串文字"I don't want this cleared, but completely gone"很可能都会驻留在此处。i_want_to_delete_this

堆栈变量

局部变量和函数参数。它们出现在您的代码中。当您进入该变量的范围时会分配内存,并在您离开该范围时自动删除:

{ //beginning of the scope
    int foo = 42; // sizeof(int) bytes allocated for foo
    ...
} //end of the scope. sizeof(int) bytes relaimed and may be used for other local variables
Run Code Online (Sandbox Code Playgroud)

请注意,当优化开启时,局部变量可能会被提升到寄存器并且根本不消耗 RAM 内存。

堆变量

堆是您自己管理的唯一一种内存。在普通 C 中,您可以使用在堆上分配内存malloc并使用释放它free,例如

int* foo = (int*)malloc(sizeof(int)); //allocate sizeof(int) bytes on the heap
...
free(foo); //reclaim the memory
Run Code Online (Sandbox Code Playgroud)

请注意,它foo本身是一个局部变量,但它指向可以存储整数的堆内存的一部分。

在 C++ 中同样的事情看起来像:

int* foo = new int; //allocate sizeof(int) bytes on the heap
...
delete foo; //reclaim the memory
Run Code Online (Sandbox Code Playgroud)

当变量的存在时间必须比作用域长得多时,通常会使用堆,通常取决于一些更复杂的程序逻辑。

  • 函数所需的最大内存量是在函数入口处分配的,但如何将该内存分配给不同范围内的变量 - 这是另一回事。如果你有两个相继的作用域 `{ int x; ... } { int y; ... }` 您将仅消耗堆栈内存的“sizeof(int)”,而不是“2*sizeof(int)”。编译器知道在第一个“}”可以回收内存。不过,这种回收是“免费的”——不需要机器指令。 (3认同)