Re: Classes bigger than themselves
Matthias Hofmann wrote:
"werasm" <w_erasm@telkomsa.net> schrieb im Newsbeitrag
Yes, search for EBCO (Empty Base Class Optimisation) on wiki (I
suppose) - It is used especially for bases that contain only typedefs.
see http://www.cantrip.org/emptyopt.html. I could not find any
references on wikipedia. I also know that "C++ Templates" by Nicolai M.
Josuttis and David Vandevoorde has some info.
I see. But what else does it mean when the standard says that applying
sizeof to a base class type yields the size of the base class type? What is
the size of a base class type? Is it possible that the following yields
zero?
class X {};
std::size_t size = sizeof ( X );
No, because X is not a base class in your example. It could be one, yes
- but it is not. Also, sizeof( X ), even if X were used as a base
class, will never return zero, because X is required to be addressable
as member (which of course it can be - however unlikely).
However, when used as a base class e.g...
struct D: X{ int member_; };
std::cout << sizeof( D ) << std::endl;
....most likely would return either 4 or 8, depending on your
architecture (32 or 64 bit). In this case, X can be optimized to have
size zero (C++ 98 par. 1.8/5).
In the case below, however - X is required to have a size...
struct D2{ X member_; int member2_ };
sizeof(D2) would now return 2*(sizeof(D)) if EBCO existed.
....else member_ and member2_ would not be seperately (uniquely)
addressable.
If not, then shouldn't the standard rather say that it returns the size of
the base class *object* rather than the size of the base class *type*?
No, because the sizeof the base class type is only optimisable when
used as baseclass (when physically (via inheritance) part of a
subobject), not in itself...
{ See note 70 in ?5.3.3/2: "The actual size of a base class subobject
may be less than the result of applying sizeof to the subobject."
-mod/aps }
Yes, exactly. "Base class subobject" must be emphasized.
class X{}; sizeof(X); //X is not a subobject yet!
class D: X{}; //X now becomes a subobject.
Kind regards (read the reference - also see the Gotcha at the end).
Werner
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]