Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm wondering how static member variables are typically implemented in languages like C++ and if their use affects the size of instantiated objects.

I know that a static members are shared by all instances of that class, but how is it shared? If it affects object size, would having 10 static variables add more size than 1?

I'm asking because I can think of two ways it might be implemented:

  • adding a pointer to static data to each object similar to the way some implementations add a pointer to the virtual function table
  • the static data is just referenced directly like a global variable with the offset being resolved by the linker / loader
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
290 views
Welcome To Ask or Share your Answers For Others

1 Answer

In C++, static members don't belong to the instances of class. they don't increase size of instances and class even by 1 bit!

struct A
{
    int i;
    static int j;
};
struct B
{
    int i;
};
std::cout << (sizeof(A) == sizeof(B)) << std::endl;

Output:

1

That is, size of A and B is exactly same. static members are more like global objects accessed through A::j.

See demonstration at ideone : http://www.ideone.com/YeYxe


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

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.

$9.4.2/3 and 7 from the Standard,

once the static data member has been defined, it exists even if no objects of its class have been created.

Static data members are initialized and destroyed exactly like non-local objects (3.6.2, 3.6.3).

As I said, static members are more like global objects!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...