Question

If I have a class with a static variable:

class A {
  public:
    ...
  private:
    static int var;
}

Will multiple instances of class A use the same address for the static variable var? If not, will defining the variable as a pointer result in the same address? I.e.:

class A {
  public:
    ...
  private:
    static int* var;
}
Was it helpful?

Solution 2

All instances of class A will share the same instance of var regardless. If we look at the draft C++ standard section 9.4.2 Static data members paragraph 1 says(emphasis mine):

A static data member is not part of the subobjects of a class. If a static data member is declared thread_local there is one copy of the member per thread. If a static data member is not declared thread_local there is one copy of the data member that is shared by all the objects of the class.

furthermore paragraph 2 says:

[...][ Note: Once the static data member has been defined, it exists even if no objects of its class have been created. [...]

OTHER TIPS

All instances of a class will use the same copy and thereby address of the static variable. If doesn't matter if you declare it a pointer or not.

All instances will see the same address for a static variable as there is only a single instance of that variable (that's the whole point of a static variable). Obviously if there is only one instance, it can only exist in one place. And it doesn't matter if it is an int or a pointer, for the pointer you just have one instance of the pointer that you can use.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top