我最近問了一個關於StackOverflowExeptions的問題,這個解釋非常有幫助!
不過,我寫了一個方法,試圖找出其中T cached
分配(堆/堆棧):分配在堆或棧上?
private Dictionary<Type, Component> _cachedComponents = new Dictionary<Type, Component>();
public T GetCachedComponent<T>() where T : Component {
//Not yet sure if the next line works or throws an exception -> just ignore it
if(_cachedComponents[typeof(T)] != null) {
return (T)_cachedComponents[typeof(T)]
} else {
T cached = this.GetComponent<T>();
_cachedComponents.Add(typeof(T), cached);
return cached;
}
}
- 由於
T cached
是我認爲它是在棧上分配的方法內聲明,對不對? - 但是,引用然後被添加到字典中,這應該被分配在堆上,對吧?
- 該方法返回後堆棧被「清除」,對吧?
- 但是
T cached
會發生什麼?
它會被移動到堆?
(因爲棧不「攜帶數據」了,但字典仍持有的引用)
Aaaaaaah。不可以。您應該仔細查看有關引用類型和值類型的各種問題。 – xanatos
[該堆棧是一個實現細節](http://blogs.msdn.com/b/ericlippert/archive/2009/04/27/the-stack-is-an-implementation-detail.aspx)試圖想到使用它的程序通常不是正確的心態。 – Servy
[內存分配:堆棧vs堆?]的可能的重複(http://stackoverflow.com/questions/4487289/memory-allocation-stack-vs-heap) –