开发者

reference objects on the stack

开发者 https://www.devze.com 2023-02-20 09:15 出处:网络
Does C# allow you to put reference objects on the stack? Why would you want to do that? What does this m开发者_开发百科ean?It\'s implementation-specific - it\'s up to the C# compiler to decide how to

Does C# allow you to put reference objects on the stack? Why would you want to do that? What does this m开发者_开发百科ean?


It's implementation-specific - it's up to the C# compiler to decide how to translate the source code into its target platform, and the C# spec doesn't guarantee how objects are allocated. Assuming an IL backend, it's then up to the execution engine to really decide how memory is allocated, within the bounds of the generated IL. (There are some clearer guarantees there, I believe, but I doubt that it prohibits future optimizations.)

The closest I know of anything like that is stack allocating arrays, which is only available in unsafe code, and I don't believe you can really get a normal reference to the array afterwards anyway.

As for why you'd want to do such a thing - presumably if you could guarantee that nothing but your current method was interested in an object, you'd like to make use of fast allocation and not bothering the GC...


No, reference objects can only live on the heap (i. e. allocated via new).

In C++ you might want an object on the stack to avoid allocation/deallocation/reference tracking hassles. Unless the object is to be used outside of the current function, there's no reason to have it on the heap. In C#, given its garbage-collected nature, lifetime tracking is not a concern.


Well the reference to your object is always on the stack. If you want the entire object to reside on the stack, you could define it as a struct instead of a class

As to why you would want to do that, if this is an object that used a lot, you might be able to increase performance by having the object reside in the stack instead of accessing the heap.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号