| 发表于:2008-01-21 21:45:145楼 得分:50 |
class x {}; in practice is never empty. rather it has an associated size of 1 byte梐 char member inserted by the compiler. this allows two objects of the class, such as x a, b; if ( &a == &b ) cerr < < "yipes!" < < endl; to be allocated unique addresses in memory. class y : public virtual x{}; class z : public virtual x{}; this size, however, is partially machine dependent. it also depends in part on the compiler implementation being used. the given size of both class y and class z on any machine is the interplay of three factors: 1. language support overhead. there is an associated overhead incurred in the language support of virtual base classes. within the derived class, this overhead is reflected as some form of pointer, either to the virtual base class subobject or to an associated table within which either the address or offset to the virtual base class subobject is stored. on my correspondent's machine, the pointer is 4 bytes. 2. compiler optimization of recognized special cases. there is the 1 byte size of the virtual base class x subobject also present within y (and z). traditionally, this is placed at the end of the "fixed" (that is, invariant) portion of the derived class. some compilers now provide special support for an empty virtual base class (the paragraph following item 3 discusses this in more detail). our correspondent's compiler, however, did not provide this special handling. 3. alignment constraints. the size of class y (and z) at this point is 5 bytes. on most machines, aggregate structures have an alignment constraint so that they can be efficiently loaded from and stored to memory. on my correspondent's machine, alignment of an aggregate is on a 4-byte boundary. so class y (and z) requires 3 bytes of padding. the result is a final size of 8. | | |
|