
On Fri, 05 Oct 2007 00:40:24 +0200, Giovanni Piero Deretta <gpderetta@gmail.com> wrote:
On 10/5/07, Marco <mrcekets@gmail.com> wrote:
About portability this is what the standard (9.2/12) says :
Nonstatic data members of a (non-union) class declared without an intervening /access-specifier/ are allocated so that later members have higher addresses within a class object. The order of allocation of nonstatic data members separated by an /access-specifier/ is unspecified. 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 classes.
as recently pointed out to me by Sebastian Redl.
template <typename T> struct point2d { T x, y; T& operator[](int i) { return (&x)[i]; } };
In the struct point2d there is no virtual functions, between data members there is no intervening access specifier, so if sizeof(T) is a multiple of the used alignment the standard guarantes that such code is valid, and this condition is verified for T = int, long, float, double using the default alignment (4 bytes).
I do not think that the standard guarantees the lack of padding between 'x' and 'y'. IIRC You are only guaranteed that &x < &y, not that &x +1 == &y.
gpd
IMO, it's a subtle question. Formally you're right about what standard guarantees, but in the above struct members x, y have the same type T, so data alignment require no padding at all. What should be put between x and y ? IMO padding is required to manage data alignment. Are there other cases where padding is needed ? Regards, Marco -- Using Opera's revolutionary e-mail client: http://www.opera.com/mail/