我最近问了一个关于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) –