I posted a question recently: Initializa开发者_如何学Ction of Static Class members.
Now please check this code:
#include<iostream>
class A
{
static int obj_s;
public:
A()
{
obj_s++;
std::cout << A::obj_s << "\nObject(s) Created\n";
}
};
int A::obj_s = 0;
int main()
{
}
Even though one has not created any object of Class A, making the member obj_s
hold a value 0
- wouldn't it need memory since its getting defined?
Obviously, it takes memory. And int A::obj_s=0
is exactly what it does: it defines the variable along with it's memory. In fact, when we say we defined a variable X
, that means we define a memory of sizeof(X)
, and that memory region we label as X
.
More about static members:
A::obj_s
is a static member of the class A
. And static members exist without any instance. They're not part of instances of A
.
§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).
Read my complete answer here:
Do static members of a class occupy memory if no object of that class is created?
The member obj_s
is static this means it is defined independently of the class.
The line:
int A::obj_s=0;
Not only defines its value but also defines the memory it uses.
That is why in the previous question you were getting a linker error (no space had been allocated for 'obj_s`. Now that you have added the line the compiler is defined the memory location(s) used by the object and the program now links.
Since the class is never instantiated, the constructor will be omitted at the link stage, and therefore probably so will the static member, since it is only ever referenced by the constructor.
I'm not 100% sure of the above statement. My biggest uncertainty is whether the zero-initialisation constitutes a reference.
EDIT: Scratch that. I just tested and found that gcc emits the static object into the final executable, even when it isn't used at all.
EDIT 2: It just occurred to me that if the class's methods and static member are all defined in a separate compilation unit, they will in fact be elided from the final executable. They only pop up in the test case because the linker only prunes at the compilation-unit level, not individual symbols.
EDIT 3: No, scratch even that. It seems that gcc wants to link against every .o, even those that aren't referenced directly or indirectly by main()
. You learn something new every day.
精彩评论