Why are the static members of a class the same for

2019-06-25 17:38发布

问题:

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

回答1:

Because they would be instance members then.

The primary characteristic of static members is that they're shared by all the instances of the class.



回答2:

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?



回答3:

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



回答4:

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.



回答5:

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.



回答6:

Because that's what static means in that context.



回答7:

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



标签: c++ class static