C# return struct reference from method

后端 未结 2 549
独厮守ぢ
独厮守ぢ 2021-01-25 04:43

In C++, returning a reference of an object allocated on the stack in a method, yields garbage values due to the fact, that the stack object is destroyed as soon the method leave

2条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-25 05:19

    I think you should read this: http://mustoverride.com/ref-returns-and-locals/

    In short, the C# Design team decided to disallow returning local variables by reference.

    – Disallow returning local variables by reference. This is the solution that was chosen for C#. - To guarantee that a reference does not outlive the referenced variable C# does not allow returning references to local variables by reference. Interestingly, this is the same approach used by Rust, although for slightly different reasons. (Rust is a RAII language and actively destroys locals when exiting scopes)

    Even with the ref keyword, if you go ahead and try this:

    public struct Test
    {
        public int a;
    }
    
    public ref Test GetValueByRef()
    {
        var test = new Test();
        return ref test;
    }
    

    You will see that the compiler errors out with the following:

    Cannot return local 'test' by reference because it is not a ref local

提交回复
热议问题