我不明白什麼時候應該在堆上分配內存以及何時應該在堆棧上分配內存。我真正知道的是,在堆棧上分配速度更快,但由於堆棧較小,我不應該使用它來分配大型數據結構;在決定分配內存的位置時應考慮哪些其他事項?編輯:我應該在哪裏分配實例變量?什麼時候應該在堆上分配? (C++)
3
A
回答
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
當您在編譯時知道您需要的存儲空間有多大才能使用堆棧作爲存儲空間。由此可見,你可以使用堆棧
- 單個對象(像你這樣的聲明局部
int
或double
或MyClass 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的整數的整數。也可以在堆棧中執行此操作,但它被認爲是不安全的,並且您可能會收到此網站命名的錯誤。
相關問題
- 1. 我們什麼時候應該上課,什麼時候不應該上課
- 2. 什麼時候應該在Objective C類上使用前綴?
- 3. 什麼時候應該使用async/await,什麼時候不用?
- 4. 什麼時候應該使用sed,什麼時候應該使用awk
- 5. 什麼時候應該擴展NSDocument,什麼時候應該擴展NSWindowController?
- 6. 什麼時候應該使用memcpy,什麼時候應該使用memmove?
- 7. 什麼時候應該使用Import-Package,什麼時候應該使用Require-Bundle?
- 8. 什麼時候應該使用AWS,什麼時候不使用
- 9. 在C#中,什麼時候應該使用一個結構,什麼時候應該使用一個類?
- 10. 什麼時候應該在android
- 11. 什麼時候應該使用UdpClient.BeginReceive?什麼時候應該在後臺線程上使用UdpClient.Receive?
- 12. C++元編程,爲什麼和什麼時候應該使用?
- 13. 什麼時候應該使用geom_map?
- 14. 什麼時候應該使用@android:id /?
- 15. 什麼時候應該拋出異常?
- 16. SqlCommand.Prepare()做什麼以及它應該在什麼時候使用?
- 17. 架構應該在什麼時候分層?
- 18. 什麼時候應該將JSON分成更小的部分?
- 19. 我們應該什麼時候在C#中使用事件
- 20. 什麼時候應該out和ref參數在C#中使用?
- 21. C++ - 什麼時候應該在類中使用指針成員
- 22. 什麼時候應該在C#中使用屬性?
- 23. 什麼時候應該在C++/CX中使用ref類?
- 24. 什麼時候應該在C++中使用字面類?
- 25. 什麼時候應該在objective-c中使用nil?
- 26. 什麼時候應該在objective-c中釋放這些對象?
- 27. 什麼時候應該使用FSharpFunc.Adapt?
- 28. 什麼時候應該關閉SolrSearcher?
- 29. 什麼時候應該使用_aligned_malloc()?
- 30. 什麼時候應該使用`use`?
重複http://stackoverflow.com/questions/599308/proper-stack-and-heap-usage-in-c – 2010-07-01 22:03:07