C++ class and object - memory
Whcih occupies memory, a class
or an object
? And, is that开发者_Go百科 at compile
or execution
time?
Thanks.
During compilation, the layout of memory is an implementation detail--you don't need to know or care.
During runtime, however... in C++, classes define types but (unless you activate RTTI which allows limited introspection into classes) don't generally occupy any memory themselves1--they're just the frameworks for the construction and destruction of objects. Their methods, however--the constructors, destructors, instance methods, and class methods, occupy some portion of executable memory, but compilers can and do optimize away any such methods that are not used in the program.
Instances of types (that is, objects as well as primitives like int
variables) occupy the bulk of memory in C++, but for their member functions they refer back to their classes. Exactly how much memory an instance of a particular class uses is entirely and utterly an implementation detail, and you should generally not need to care about it.
1 Even then, the classes themselves don't use the memory, but their associated std::typeinfo
instance does. But again, this is generally implementation-y stuff and not the sort of thing even wizened programmers pay much attention to.
The object instance
is the one which occupies memory at execution time since a class
is the blueprint of the object.
Also, in C++ there are static variables, local variables and global variables which also occupies memory.
Static, local and global variables are stored in BBS data segment, while objects are stored either in heap or in stack. Objects are the instances of class, while class definition is used by compiler to create an object by it's class description. Class is like an instruction of "how to build table by yourself" that occupies only the paper it's written on, while an object is the real table made by yourself according to the instruction, that occupies the real space.
精彩评论