Why are the static members of a class the same for

2019-06-25 17:21发布

Why don't we have different copies of static variables for the different objects?

标签: c++ class static
7条回答
放我归山
2楼-- · 2019-06-25 17:31

That is the definition of static - one copy of the data exists. It is separately stored, most likely along with all the other static data of the library or application.

查看更多
趁早两清
3楼-- · 2019-06-25 17:35

Because class static members are stored separately in BSS section, so every instance of a class has the same value.

查看更多
Ridiculous、
4楼-- · 2019-06-25 17:42

Because the section $9.4.2/1 from the C++ Standard (2003) says,

A static data member is not part of the subobjects of a class. There is only one copy of a static data member shared by all the objects of the class.

Since the Standard alone decides what C++ is, what not, so it's how C++ has been designed!

Static members are more like global objects. The same copy belong to all objects!

See this post for detail answer : Do static members of a class occupy memory if no object of that class is created?

查看更多
We Are One
5楼-- · 2019-06-25 17:45

Because that's what static means in that context.

查看更多
狗以群分
6楼-- · 2019-06-25 17:46

A static member is not associated with a specific instance.

If you want different values of the member for each instance you should use instance members (remove the static keyword).

查看更多
\"骚年 ilove
7楼-- · 2019-06-25 17:52

It's by definition- a static object is one that's shared by all instances of the class. Regular members don't have this property.

查看更多
登录 后发表回答