C++ Logo

sg12

Advanced search

Re: [ub] Type punning to avoid copying

From: Nevin Liber <nevin_at_[hidden]>
Date: Mon, 29 Jul 2013 16:53:03 -0500
On 26 July 2013 20:07, Jeffrey Yasskin <jyasskin_at_[hidden]> 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_[hidden]>  (847) 691-1404

Received on 2013-07-29 23:53:44