如何为静态变量分配内存? [英] How is memory allocated for a static variable?

查看:38
本文介绍了如何为静态变量分配内存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的程序中:

class Main
{   
    static string staticVariable = "Static Variable";
    string instanceVariable = "Instance Variable";

    public Main(){}   
}

instanceVariable 将存储在为对象实例分配的内存中.staticVariable 将存储在哪里,它是存储在对象实例本身还是其他地方?如果它存储在其他地方,内存位置是如何连接的?

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?

推荐答案

静态变量的内存通常保存在一些有根(和隐藏)的 object[] 中.这可以看到在 WinDbg 中的对象上执行 !gcroot(使用 SOS).

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).

补充一点,正如我最近发现的那样,这些引用永远不会被 GC 处理(除非您将字段清空).

Just to add, these references can never be GC'ed (unless you null the field), as I discovered recently.

这篇关于如何为静态变量分配内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆