2010-07-01 72 views
3

我不明白什麼時候應該在堆上分配內存以及何時應該在堆棧上分配內存。我真正知道的是,在堆棧上分配速度更快,但由於堆棧較小,我不應該使用它來分配大型數據結構;在決定分配內存的位置時應考慮哪些其他事項?編輯:我應該在哪裏分配實例變量?什麼時候應該在堆上分配? (C++)

+0

重複http://stackoverflow.com/questions/599308/proper-stack-and-heap-usage-in-c – 2010-07-01 22:03:07

回答

4
  1. 在堆棧上分配大多數對象。生命週期==範圍。
  2. 如果您需要手動控制對象的生命週期,請將其分配到堆上。
  3. 如果對象很大並且堆棧不夠大,請將其分配到堆上。
  4. 在案例2和3中使用(嚴重名稱)RAII習慣用法,它允許您在堆棧上使用對象來操作可能是堆上對象的資源 - 一個很好的例子是智能指針,如std :: shared_ptr的/升壓:: shared_ptr的。
+0

我想添加一些東西。 5.如果你進入C++ 0x,你也可以看看unique_ptr <>。我個人認爲運動語義非常乾淨。這不會像shared_ptr一樣有用,但unique_ptr <>有一些非常有用的語義,可以保持它的高效性。 – Dragontamer5788 2010-07-01 22:18:17

2

當內存必須超出當前函數的範圍時才使用堆。

0

當您在編譯時知道您需要的存儲空間有多大才能使用堆棧作爲存儲空間。由此可見,你可以使用堆棧

  • 單個對象(像你這樣的聲明局部intdoubleMyClass temp1;可變
  • 靜態大小的數組(當你聲明char local_buf[100];MyDecimal numbers[10];
像你一樣

必須當你只知道你在運行時需要多少空間時使用堆(「免費商店」),而你應該可能使用堆大靜態已知的緩衝液(如char large_buf[32*1024*1024];

但是通常情況下,你非常應罕直接觸摸堆,但通常使用管理一些堆內存給你(和對象的對象可能住在堆棧或作爲另一對象的成員 - 在那裏你那麼不在乎其他對象的生活)

給一些示例代碼:

{ 
char locBuf[100]; // 100 character buffer on the stack 
std::string s; // the object s will live on the stack 
myReadLine(locBuf, 100); // copies 100 input bytes to the buffer on the stack 
s = myReadLine2(); 
    // at this point, s, the object, is living on the stack - however 
    // inside s there is a pointer to some heap allocated storage where it 
    // saved the return data from myReadLine2(). 
} 
// <- here locBuf and s go out-of-scope, which automatically "frees" all 
// memory they used. In the case of locBuf it is a noop and in the case of 
// s the dtor of s will be called which in turn will release (via delete) 
// the internal buffer s used. 

因此,爲了給一個簡短的回答你的問題不要分配堆上的任何東西(通過new),除非這是通過適當的包裝對象完成。 (std :: string,std :: vector等)

0

根據我的經驗,當你希望在運行時聲明一個對象數組的大小時,堆分配是最有用的。

int numberOfInts; 
cout << "How many integers would you like to store?: "; 
cin >> numberOfInts; 
int *heapArray = new int[numberOfInts]; 

這段代碼會給你一個大小爲numberOfInts的整數的整數。也可以在堆棧中執行此操作,但它被認爲是不安全的,並且您可能會收到此網站命名的錯誤。

相關問題