Boost logo

Boost :

From: Sebastian Redl (sebastian.redl_at_[hidden])
Date: 2007-10-02 09:01:36


Marco wrote:
> Are you speaking about rules provided in the C++ ISO standard ? Could you
> point me to them ? (page, section). I'd like to give them a look .
>
Reinterpret_cast is defined in 5.2.10. The language there is rather
clear about what is guaranteed and what not. Judging by that section,
you can't rely on the results of the cast for anything except casting it
back.

Layout compatibility is defined in various sections of the standard.
They are first mentioned in 3.9/11, where it says that a type is
layout-compatible with itself. In 3.9.2/3 it says that pointers to
layout-compatible types must have the same value representation and
alignment requirements. 7.2/7 defines layout compatibility for
enumerations; 9.2/14+15 do it for structures and unions.

9.2/16 is where it gets interesting. It says that, if two structs in a
union share a common initial subsequence of layout-compatible types, you
can access the fields of this sequence through either struct name.

9.2/17 makes an implicit guarantee about casts, even though nothing in
chapter 5 (where casts are defined) really allows this. It says:
> A pointer to a POD-struct object, suitably converted, points to its
> initial member (or if that member is a bit-field, then to the unit in
> which it resides) and vice versa.
In other words, given

struct foo { int i; };

you can do

foo f = {4};
foo *pf1 = &f;
int *pi = reinterpret_cast<int*>(pf1);
cout << *pi;
foo *pf2 = reinterpret_cast<foo*>(pi);
cout << pf2->i;

The implicit guarantee is there because there is no other way to convert
the pointer except through a reinterpret_cast. (A C-style cast is
defined in terms of the cast operator is takes the place of.)

Layout compatibility is not mentioned anywhere else. So what does that mean?

It means that, by the words of the standard, your code was not valid. On
the other hand, making both structs the members of a union, then
assigning one and reading the other, is valid. Make of that what you will.

Sebastian Redl


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk