lua-users home
lua-l archive

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

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 <> wrote:
>>>>> "Viacheslav" == Viacheslav Usov <> 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[].



Sent from my phone