user1013944
user1013944

Reputation:

What does it mean to be stored as an object in memory?

In TC++PL, The author says

If and only if you use an initialized (static) member in a way that requires it to be stored as an object in memory, the member must be uniquely defined somewhere.

However, I have no idea what it means to be stored as an object in memory. I guess the static member is already in memory whether the object of its class is instantiated. For your information, the author introduces an example.

class Curious {
public:
    static const int cl = 7;
    ....
}
const int Curious::cl;

It looks like some kind of instantiation. However, I don't know why it's necessary. We can simply access Curious::cl directly.

Upvotes: 1

Views: 136

Answers (1)

Mats Petersson
Mats Petersson

Reputation: 129364

Now, let's also say that class Curious is in a headerfile, which is included in 6 different source files (s1.cpp to s6.cpp to give them a name).

And we need to, for some "good reason" take the address of cl...

In what place should the compiler put this the cl variable? Note that when the compiler does it's job, it (typically) can only see one source file at a time, so it has no idea how many times the Curious class definition, and thus the static const int cl = 7; has occurred in the code. So it can't say "Oh, I have a cl in s1.cpp, so when I'm compiling s2.cpp ... s6.cpp, I don't need one".

In other words, the compiler needs your help to "place" the cl into an object file.

[This can get even more interesting in an embedded system, where data may well be in different "sections" of memory depending on which source file you compile it as, so the memory chosen for cl could change depending on which source file you use. In "bigger" computers, this is much less of an issue, but still, the language definition doesn't know how you are going to use the language, so has to cater for various variants where it may matter].

Upvotes: 3

Related Questions