Is a C# struct ever boxed when declared as the return value of a function?

廉价感情. 提交于 2019-12-19 05:56:45

问题


A simple question, but I haven't found a definitive answer on Stack Overflow.

    struct MyStruct { int x, y, z; }

    MyStruct GetMyStruct() => new MyStruct();

    static void Main()
    {
        var x = GetMyStruct();      // can boxing/unboxing ever occur?
    }

Is a C# struct (value type) always copied to the stack when returned from a function, no matter how large it might be? The reason I'm unsure is that for some instruction sets other than MSIL (such as x86), a return value usually needs to fit into a processor register, and the stack is not directly involved.

If so, is it the call site that pre-allocates space on the CLR stack for the (expected) value return type?

[edit: summary of replies:] For the intent of the original question, the answer is no; the CLR will never (silently) box a struct just for the purpose of sending it as a return value.


回答1:


It is a heavy implementation detail of the JIT compiler. In general, if the struct is small enough and has simple members then its gets returned in CPU registers. If it gets too big then the calling code reserves enough space on the stack and passes a pointer to that space as an extra hidden argument.

It will never be boxed, unless the return type of the method is object of course.

Fwiw: this is also the reason that the debugger cannot display the return value of the function in the Autos window. Painful sometimes. But the debugger doesn't get enough metadata from the JIT compiler to know exactly where to find the value. Edit: fixed in VS2013.




回答2:


A struct is boxed whenever you want to treat it as an object, so if you call Func and assign the result to object it will be boxed.

E.g. doing this

 object o = Func();

will yield the following IL

L_0000: call valuetype TestApp.foo TestApp.Program::Func()
L_0005: box TestApp.foo
L_000a: stloc.0 

which shows that the return value is boxed, because we assign it to a reference of the type object.

If you assign it to a variable of type Foo it isn't boxed and thus it is copied and the value is stored on the stack.

Also, boxing wouldn't really help you here since it would involve creating an object to represent the value of the struct, and the values are effectively copied during the boxing operation.



来源:https://stackoverflow.com/questions/3742922/is-a-c-sharp-struct-ever-boxed-when-declared-as-the-return-value-of-a-function

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