C# 如何为静态变量分配内存?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/337019/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How is memory allocated for a static variable?
提问by gk.
In the below program:
在下面的程序中:
class Main
{
static string staticVariable = "Static Variable";
string instanceVariable = "Instance Variable";
public Main(){}
}
The instanceVariable
will be stored inside the memory allocated for object instance. Where will the staticVariable
be stored, is it stored in the object instance itself or somewhere else? If its stored somewhere else, how are the memory locations connected?
在instanceVariable
将存储分配给对象实例的记忆里。将staticVariable
存储在哪里,它是存储在对象实例本身还是其他地方?如果它存储在其他地方,内存位置是如何连接的?
采纳答案by leppie
Memory for static variables are normally held in some rooted (and hidden) object[]
. This can be seen doing a !gcroot on the object in WinDbg (with SOS).
静态变量的内存通常保存在一些有根的(和隐藏的)中object[]
。这可以看到在 WinDbg 中的对象上执行 !gcroot(使用 SOS)。
Just to add, these references can never be GC'ed (unless you null the field), as I discovered recently.
补充一点,正如我最近发现的那样,这些引用永远不会被 GC 处理(除非您将该字段设为空)。
回答by Nick Borodulin
For instance in C++ staic variables are allocated in global memory space with global variables. Compiler uses special naming convention to know that this variable belongs to the class.
例如,在 C++ 中,静态变量在全局内存空间中与全局变量一起分配。编译器使用特殊的命名约定来知道该变量属于该类。