I recently asked a question about StackOverflowExeptions and the explanations were very helpful!
However, I wrote a method and tried to figure out where T cached
is allocated (heap/stack):
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;
}
}
- Since
T cached
is declared inside the method I assume it is allocated on the stack, right? - But the reference is then added to the dictionary, wich should be allocated on the heap, right?
- The stack is "cleared" after the method returns, right?
- But what happens to
T cached
?
Is it going to be moved to the heap?
(Because the stack does not "carry the data" anymore but the dictionary still holds a reference)