C++ Logo


Advanced search

Re: [ub] Type punning to avoid copying

From: Gabriel Dos Reis <gdr_at_[hidden]>
Date: Fri, 26 Jul 2013 20:18:07 -0500
Jeffrey Yasskin <jyasskin_at_[hidden]> writes:


| (We do need to have the standard endorse using memcpy to set the
| object representation of a trivially-copyable struct, but I don't hear
| any disagreement about wanting that. I'll mail Ville about an EWG
| issue.)

Actually this is on my list of issues I would like to see SG12 discuss,
and our first recommendation to forward to EWG+CWG at the Chicago meeting.

| > 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.
| That's ... not the union hack. The union hack is the thing that gcc
| (http://gcc.gnu.org/onlinedocs/gcc-4.8.1/gcc/Optimize-Options.html#index-fstrict_002daliasing-881)
| and probably C99 endorse where you write one field of a union and read
| a different field. Simply casting a char[] to a different type is
| something else, which I hear more objections to simply allowing.

In fact, I would prefer to see standards support -- either in form of
library functions or in form of some language features or combination --
for object and value representation as arrays of unsigned char, along
with your bit_cast. My personal preference would be that over the
"union hack".

I am unconvinced we need to embark on a complete overhaul of the basic
C++'s object model, where the outcome would be that one would talk of an
object's value before it is ever constructed.

-- Gaby

Received on 2013-07-27 03:18:24