C++ Logo

sg12

Advanced search

Re: [ub] Type punning to avoid copying

From: Nevin Liber <nevin_at_[hidden]>
Date: Fri, 26 Jul 2013 14:02:39 -0500
On 26 July 2013 13:35, Jeffrey Yasskin <jyasskin_at_[hidden]> wrote:

>
> Ah, that's too bad because it doesn't serve the purpose Ion was asking
> about. He wanted a memory buffer with known contents to become the
> object representation of an object of a particular type.


+1.

This is a real issue for anyone that has to interpret binary data from a
hardware device, a network connection or a file. There needs to be an easy
to program way of accomplishing this; one shouldn't have to consult the C++
Committee or be an expert on undefined behavior to guess if the code is
correct, and one shouldn't have to manually look at the data byte by byte
to convert it. (Besides the copying cost, one may not need all the fields
in a message, yet it is incredibly error prone to convert just the fields
you do need.)

People use the union hack because it is easy to program, given that it is
mainly declarative. Declare a struct that corresponds to the layout of the
data, cast the buffer pointer to the struct pointer, and it usually just
works. If it isn't that easy, people will just keep using the union hack.

This is one of the reasons people pick C and C++ in the first place.

One (unexplored) thought: maybe we need some magic classes to encapsulate
this, just like std::atomic hides details about atomic access.
-- 
 Nevin ":-)" Liber  <mailto:nevin_at_[hidden]>  (847) 691-1404

Received on 2013-07-26 21:03:20