Re: vtbl inheritance
On Jan 31, 3:15 pm, Pete Becker <p...@versatilecoding.com> wrote:
On 2011-01-31 09:43:33 -0500, Leigh Johnston said:
[...]
I don't think it will fail in this particular case, because of
the data types involved and their respective alignment
requirements. But in general, the actual number of bytes
occupied by UnitHeader may be less than sizeof(UnitHeader) when
UnitHeader is a base class, so brutally writing
sizeof(UnitHeader) bytes is not a safe operation. (The "empty
base class optimization" is somewhat miss-named, because it
doesn't apply to only empty base classes.)
What is this nonsense? A base subobject is an object and in this case
the object is POD and it is fine to memset a POD object with sizeof(POD
object type) bytes.
Where can you find that in the standard? The definition of
sizeof (=A75.3.3) says that "The result of applying sizeof to
a base class subobject is the size of the base class type."
I can find no words which guarantee that a base class subobject
actually occupies all of these bytes, and there is at least one
specific case (an empty base class) where this is not required.
struct S { };
struct T : S { int i; };
T t;
Clause 9 [classes]/3: "Complete objects and *member* subobjects of
class type shall have nonzero size" [emphasis added]. So sizeof(S) is
required to be at least 1. But when S is used as a base class of T the
resulting subobject is neither a complete object nor a member subobjct,
so it is not required to have nonzero size. That's the "empty base
class optimization". It allows objects of type T to occupy sizeof(int)
bytes, with the S subobject taking up no space. If the compiler does
that, calling memset((S*)&t, '\0', sizeof(S)) will write 1 byte into t,
which will overwrite one of the bytes of t's int member.
But is this liberty really only restricted to empty base
classes. Given something like:
struct B { double d; char c; };
struct D : B { int i; };
and the alignment requirements double -> 8 and int ->4, could
an implementation lay it out with the offset of D::i at 12, even
though sizeof B is 16. This is what I would expect; that the
freedom given for empty base classes was general. And I can't
really find any text forbidding it.
--
James Kanze