为什么 stackalloc 接受可变长度?

Why stackalloc accepts a variable length?

知道为什么 'stackalloc' 关键字接受可变长度吗?

如果此指令 returns 指向分配在堆栈帧中的缓冲区的指针,编译器如何管理它?每次调用组织堆栈帧时,它都会在运行时重新编译函数?

谢谢。

Any idea why the stackalloc keyword accepts a variable length?

因为这样做很有用且值得期待,因此语言设计者选择允许它。

If this instruction returns a pointer to a buffer allocated in the stack's frame, how the compiler manage that? It recompiles the function at runtime every time it's called to organize the stack frame?

localalloc 指令在 堆栈当前帧之后分配内存 ,分配只是将地址存储回本地。因此:没有必要重新计算任何东西,除了更新堆栈框架的末尾,这样如果我们调用另一个方法它就不会被覆盖。

(注意:与往常一样,在讨论堆栈时,这实际上是一个实现细节;JIT 在理论上可以自由地从任何地方分配它,只要它尊重语义)