Why are the static members of a class the same for all objects?
Why don't we 开发者_如何学JAVAhave different copies of static variables for the different objects?
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.
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?
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).
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.
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.
Because that's what static
means in that context.
Because class static members are stored separately in BSS section, so every instance of a class has the same value.
精彩评论