Re: Memory layout and inheritance
Mathias Gaunard wrote:
On Mar 1, 11:10 am, "James Kanze" <james.ka...@gmail.com> wrote:
On Feb 28, 11:38 pm, "Mathias Gaunard" <loufo...@gmail.com> wrote:
Why, in the following code, is sizeof(Foo) different from sizeof(B) ?
The real question is why you expect them to be the same.
Because I would expect my compiler to make the more efficient
layout for Foo, considering both space and alignment
requirements.
It makes the most efficient layout it can, considering both
space and alignment.
And the more efficient layout for B would be Foo.
It seems
struct B : public A
{
/* some things */
};
is actually implemented as
struct B
{
A some_name;
/* some things */
};
Of course it is. Nothing else works.
which is less efficient than "inlining" the members of A, simply
because the non-used space of A induced by its alignment can't be
reused.
If you don't require the code to work, then you can optimize a
lot of things.
The standard already has a few exceptions where code is not
required to work: the empty base class optimization, and the
eliding of copy constructors. You're arguing for it to add
more.
Your A was a POD. Consider what happens when you memcpy into
it. Even if it wasn't, consider what happens when you copy it,
while initializing the elements of B differently.
A compiler can optimize for speed or for space. Optimized for
space, on an Intel, the size of Foo and the size of B would be
the same. And the size of A would be 5. Optimize for speed,
and you need to respect alignment. Most compilers today
optimize for speed, at least by default.
struct B
{
/* the members of A */
/* some things */
};
has the same capabilities and is more efficient.
You can still cast a B* to an A* safely.
But you can't use the A* safely. For example:
static A someA ;
B someB ;
*static_cast< A* >( &someB ) = someA ;
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient?e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S?mard, 78210 St.-Cyr-l'?cole, France, +33 (0)1 30 23 00 34
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]