Re: In-memory order of class variables
On 2008-11-21 14:19, Daniel Kr??gler wrote:
On 21 Nov., 02:34, Alberto Ganesh Barbati <AlbertoBarb...@libero.it>
irotas ha scritto:
Consider the following class:
Is it always, no matter what, infallibly true, that Foo::a will appear
in memory *before* Foo::b, and Foo::b before Foo::c? (I'm talking
about userland here, not kernel)
I always assumed that to be true, but someone told me recently that
they thought that some architectures might reorder the variables in
memory (if the compiler is configured to pack struct's) in order to
obtain an optimal memory footprint.
This "someone" is wrong. 9.2/12 says that explicitly:
So the only reordering allowed is due to the presence of
access-specifiers. For example an implementation may decide store all
private members before all public members, regardless of the declaration
order. For what it's worth, I'm not aware of any implementation that
exploits this possibility.
What you say is right regarding the OP's example, but to be fair, the
OP is right that the current official standard 14882:2003(E) has one
further saying to that in 11.1 [class.access.spec]/2:
"The order of allocation of data members with separate access-
labels is unspecified (9.2)."
which is probably the reason for the "someone" to mention that point.
It could happen (according to the old wording), if you define Foo
seemingly equivalent as
Both paragraphs have been fixed regarding this situations as part of
11.1/2 has been removed and now the draft says in 9.2/12
"Nonstatic data members of a (non-union) class **with the same access
control** (Clause 11) are allocated so [..]"
"Nonstatic data members of a (non-union) class declared **without an
intervening access-specifier** are allocated so [..]"
Nonstatic data members of a (non-union) class with the same access
control are allocated so that later members have higher addresses
within a class object. The order of allocation of non-static data
members with different access control is unspecified.
I'm wondering, given the following class:
int a, b;
int x, y;
Does the standard allow the members to be laid out like this: a x b y?
Obviously this is not the intention but I do not see that it's forbidden
either. I suppose that the rest of the paragraph:
Implementation alignment requirements might cause two adjacent members
not to be allocated immediately after each other; so might
requirements for space for managing virtual functions and virtual base
could disallow it if you consider the list of reasons to be exhaustive.
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]