stackalloc 表达式的 return 类型是什么?

What is the return type of a stackalloc espression?

我正在玩 stackalloc 并发现它的 return 类型有很多奇怪之处。下面是一些使用 stackalloc<float>:

的例子

1. 隐式类型 returns float*:

var a = stackalloc float[1];//a is float*

2. 声明一个 float* 并稍后使用 stackalloc 设置它不会编译:

    float* a;
    a = stackalloc float[1];//CS8346 conversion of a stackallock expression of type 'float' to type 'float*' is not possible

3. 在初始化的同时声明 float* 就好了:

float* a = stackalloc float[1];

4. 类似的行为发生在 Span<float>

这很好用:

 Span<float> a = stackalloc float[1];

但这不能编译:

        Span<float> a; 
        a = stackalloc float[1];//CS8353 A result of a stackalloc expression of type 'Span<float>' cannot be used in this context because it may be exposed outside of the containing method

5. 让整个情况更奇怪的是 Span<float>float* 之间没有隐式转换,反之亦然。

那么 stackalloc float[1] return 到底是什么?为什么会出现上述行为?

此代码是使用 VS 2019 C# 9.0 版、.NET 5 编写的。

根据C# 6 draft specification stackalloc:

In an unsafe context, a local variable declaration (Local variable declarations) may include a stack allocation initializer which allocates memory from the call stack.

即它只能用于您称为“内联”的声明。

根据 language reference stackalloc 没有单独定义的 return 类型但是“在堆栈上分配一块内存”然后:

You can assign the result of a stackalloc expression to a variable of one of the following types:

  • Beginning with C# 7.2, System.Span<T> or System.ReadOnlySpan<T>
  • A pointer type

一些有趣的额外链接: