简体   繁体   English

静态数据成员与全局变量之间的区别

[英]Difference between static data member and global variable

Variations of this question might have been asked earlier as well. 这个问题的变体也可能早些时候被问过。 This question is about static data member vs global variable not static variable vs global variable. 这个问题是关于静态数据成员与全局变量而不是静态变量与全局变量。

All of us know what static data member and global variables do. 我们所有人都知道静态数据成员和全局变量的作用。 How compilers link them, where they get mapped in memory layout, their default values etc. When I think about them I do not have a clear picture of the possible scenarios where we should use static data member instead of global variable. 编译器如何链接它们,它们在内存布局中的映射位置,它们的默认值等。当我想到它们时,我不清楚应该使用静态数据成员而不是全局变量的可能情况。

I thought of one use case where you want to count the number of objects created for a class. 我想到了一个用例,其中您要计算为一个类创建的对象数。 You make one static data member and increase in the ctor whenever you create an new object. 您创建一个静态数据成员并在创建新对象时增加ctor。 But at same thought, we could also do the same thing, counting of the created objects, with the global variable as well. 但是出于同样的想法,我们还可以使用全局变量对创建的对象进行计数,从而完成相同的操作。

So, it is not clear to me till now that what are the use cases of using static data member vs global variable? 因此,到目前为止我还不清楚使用静态数据成员与全局变量的用例是什么?

They are in different scopes: 它们属于不同的范围:

  • The static data member can have visibility restriction public / protected / private . static数据成员可以具有可见性限制public / protected / private
  • The global variable can be modified without restriction 可以不受限制地修改全局变量
  • The static (global) variable can only be modified in file scope. static (全局)变量只能在文件范围内修改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM