On 29.08.2016 11:46, Alf P. Steinbach wrote:
> On 29.08.2016 09:13, Piotr Wyderski wrote:
>> Let there be an arithmetic type T and a class C { T t; };
>> Under what circumstances the conversions const T* <=>
>> const C* can be considered legal? Obviously it is not
>> so if C contains virtual methods. Is sizeof(T) == sizeof(C)
>> enough from the standard's point of view?
>
> No, size has nothing to do with it.
>
> Given a C object, the requirement is simply that `t` is the first data
> member.
Later he is talking about arrays of T, so it appears the above const T*
really refers to an array, not to a single value. And in arrays sizeof
is very relevant - sizeof is basically defined as the element spacing in
an array.
>
>> Do classes having
>> this property have a special name/traits in C++ (including C++17)?
>
> Yep, they're called "standard layout" classes.
>
> C++11 §9.2/20:
> “A pointer to a standard-layout struct object, suitably converted using
> a reinterpret_cast, points to its initial member (or if that member is a
> bit-field, then to the unit in which it resides) and vice versa.”
>
> Note that this requires that the object is originally a C.
So it appears that formally casting a T* to a C* is still undefined. I
gather that a perverse implementation might pad T and C in the end to
have equal sizeof-s, but fill the padding with different values which
are checked at run time.
>
>> The application: I have a really big collection of Ts stored on a disk,
>> but it would be most convenient to access them via the object-oriented
>> "view" C.
>
> Well, on disk is no problem: just read them into C instances' t members.
> No need to do pointer casting.
He says that the arrays are really large, so he might think of something
like memory mapping the binary file and interpret the content as const
C* instead of const T*. If so, then memory mapping and cast to 'const
T*' are already non-portable enough so that additional cast to const C*
would probably be the safest step here (assuming standard layout, T as
the first member and equal sizeof-s).