Daniel wrote:
> On Sunday, February 23, 2020 at 12:13:43 AM UTC-5, Pavel wrote:
>> Öö Tiib wrote:
>>> std::aligned_storage. ;)
>> There is nothing special I can see about std::aligned_storage with regard to
>> reinterpret_cast.
>
> Every use I've seen of std::aligned_storage has reinterpret_cast, without
> reinterpret_cast, what could you do with it?
It is difficult to say. Somehow the Standard carefully avoids ever guaranteeing
anything about the result of reinterpret_cast<T1*>(tPtr); where tPtr is of type
T* and T is different from T1.
E.g. looking at 7.6.1.9 "Renterpret Cast" in n4849 (and, I believe all previous
Standards):
3 [Note: The mapping performed by reinterpret_cast might, or might not, produce
a representation different from the original value. — end note]
...
You would think that somewhere in
7 An object pointer can be explicitly converted to an object pointer of a
different type... When a prvalue v of object pointer type is converted to the
object pointer type “pointer to cv T”, the result is static_cast<cv
T*>(static_cast<cv void*>(v)). [Note: Converting a prvalue of type “pointer to
T1” to the type “pointer
to T2” (where T1 and T2 are object types and where the alignment requirements of
T2 are no stricter than
those of T1) and back to its original type yields the original pointer value. —
end note]
the Standard would guarantee something about memory addresses like "the address
of v and the address represented by the result of reinterpret_cast<T2*>(v) are
same" but alas. The guarantees are only for some two-way applications e.g. T* to
intptr_t (see 7.6.1.9-5) and back or T1 to T2 and back.
Of course, everybody uses static_cast and reinterpret_cast for this purpose so
it probably "will just work". Wherever possible I would, however, stick to union
approach which seems to be better defined.
It is probably prudent to use it even though it may be important only when T has
some special features, see 17.6.4 "Pointer optimization barrier":
5 [Note: If a new object is created in storage occupied by an existing object of
the same type, a pointer
to the original object can be used to refer to the new object unless its
complete object is a const object
or it is a base class subobject; in the latter cases, this function can be used
to obtain a usable pointer
to the new object. ...]
>
> Daniel
>