lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Just another data point, since I recently saw it:
The well-used GLM library (which is C++) uses type punning through a
union just about as clear as can be:
    https://github.com/g-truc/glm/blob/b3f87720261d623986f164b2a7f6a0a938430271/glm/detail/func_common.inl#L722

I suppose, since it's C++ (not C90), it is technically undefined
behavior. But I have certainly worked on dozens of systems over
decades that rely on it, so it seems like extremely reliable undefined
behavior, as far as that goes (:  And of course, it is explicitly
supported by GCC.

Anyway, good to understand the rationale behind that 'volatile' stuff;
glad I wasn't missing something (too) tricky.

-John

On 10/1/20, Diego Nehab <diego@impa.br> wrote:
> I think memcpy is the safest approach. Fortunately, a good compiler is
> smart enough to optimize away the memcpy when it knows the object is
> aligned. GCC even has a built-in to let you tell the compiler about the
> alignment when it is not obvious.
>
> On Thu, Oct 1, 2020 at 06:07 Andrew Gierth <andrew@tao11.riddles.org.uk>
> wrote:
>
>> >>>>> "Viacheslav" == Viacheslav Usov <via.usov@gmail.com> writes:
>>
>>
>>
>>  Viacheslav> Moreover, in C++ union-based type punning is undefined
>>
>>  Viacheslav> behavior, and since the Lua source code intends to be
>>
>>  Viacheslav> consumable as C++, this is a problem that volatile does not
>>
>>  Viacheslav> correctly address, either.
>>
>>
>>
>>  Viacheslav> I believe memcpy() is the only way that would be truly
>>
>>  Viacheslav> portable with all those things considered.
>>
>>
>>
>> I think you are correct, though I'd be surprised if any C++ compiler did
>>
>> the wrong thing with union type punning of basic types.
>>
>>
>>
>> The C++ standard seems to have the same exception for aliasing a value
>>
>> by way of a char or unsigned char type that C has. So your example has
>>
>> one more copy than is needed - the bytes can be copied directly from or
>>
>> to the "double" var without needing the intermediate char buff[].
>>
>>
>>
>> --
>>
>> Andrew.
>>
>>
>
> --
> Sent from my phone
>