[ub] Type punning to avoid copying
Nevin Liber
nevin at eviloverlord.com
Mon Jul 29 23:53:03 CEST 2013
On 26 July 2013 20:07, Jeffrey Yasskin <jyasskin at google.com> wrote:
>
> FWIW, you do need to deal with endian-ness issues in the real world,
> and simply overlaying a struct on raw bytes *won't deal with that*,
>
Sure it will; just overlay a BigEndian<uint16_t> instead of a raw
uint16_t. Rough implementation:
// Assumes little endian machine
template<typename T>
struct BigEndian
{
operator T() const noexcept
{ return endian_swap(value); }
BigEndian& operator=(T t) noexcept
{ value = endian_swap(t); return *this; }
T value;
};
endian_swap functionality is typically provided as a compiler built in and
is starting to be included as a processor instruction (such as MOVBE on
Haswell <http://www.realworldtech.com/haswell-cpu/2/>). The efficiency is
that important to low latency and embedded work.
Is this applicable to everything? Of course not. Serialization libraries
are far more powerful, as on can use them with arbitrary objects, whereas
type punning in this respect is only useful for, at best, trivially
copyable types.
We really do need a clear statement of the current rules. Is this code
legal at all? Is it legal if one just uses POD types? Standard layout
types? Etc., etc.
--
Nevin ":-)" Liber <mailto:nevin at eviloverlord.com> (847) 691-1404
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.open-std.org/pipermail/ub/attachments/20130729/25452845/attachment.html
More information about the ub
mailing list