C# Returning local variables

老子叫甜甜 提交于 2019-12-22 04:40:50

问题


Coming from C++, returning a local variable was a bad idea (when allocated memory on the stack).

Now using C# I'm getting the impression it isn't a bad idea (when returning a value, not a reference).

Why is that? I understand C# uses the GC but I'm not sure what difference that would make in this case.


回答1:


The problem in C/C++ is that you can return a pointer to data that is located on the stack. If you do that the pointer is invalid as soon as the stack frame is destroyed. In managed C# you can't do such a thing.

Returning locals in C# is fine. If you return a value type, the value is copied. If you return a reference, the reference itself is copied (but it still points to the same object on the heap). In either case, there's no issue.



来源:https://stackoverflow.com/questions/22432584/c-sharp-returning-local-variables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!