[英]How can I delete variables in 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. */
我不明白你為什么要這樣做,並且在任何情況下你都不能刪除或以其他方式刪除命名變量,除非它們在概念上被編譯器在超出范圍時被你刪除,並且實際上被刪除了包含它們的函數退出。 例如:
{
{
string i_want_to_delete_this = "I don't want this cleared, but
completely gone";
} // it's gone
}
有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
請注意,當啟用優化時,可能會將局部變量提升為寄存器,並且根本不消耗RAM內存。
堆變量
堆是你自己管理的唯一一種記憶。 在普通的C您在使用堆分配內存malloc
與和釋放它free
,如
int* foo = (int*)malloc(sizeof(int)); //allocate sizeof(int) bytes on the heap
...
free(foo); //reclaim the memory
請注意, foo
本身是一個局部變量,但它指向堆內存的一部分,您可以在其中存儲整數。
同樣認為在C ++中看起來像:
int* foo = new (int; //allocate sizeof(int) bytes on the heap
...
delete foo; //reclaim the memory
當變量必須比范圍長得多時,通常使用堆,通常取決於一些更復雜的程序邏輯。
當執行離開函數或子語句時,將刪除自動變量,即不使用malloc
或new
運算符的變量。
在函數外部聲明的變量將保留在內存中,直到程序終止。
此外,我將專注於程序的正確性和穩健性。 如果程序不適合您的平台內存,則只擔心RAM或內存使用情況。
在現實世界中,工作場所,由程序處理並且不適合存儲器的大多數數據可以分成多個部分並且每個部分單獨處理(盡管有一些例外)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.