C++ Logo

sg12

Advanced search

Re: [ub] data overlays: reinterpret_cast vs placement new

From: Jens Maurer <Jens.Maurer_at_[hidden]>
Date: Wed, 19 Mar 2014 22:25:13 +0100
On 03/18/2014 06:06 AM, David Krauss wrote:
> I have a POD data overlay class template whose only member is a char[]. It performs byte swapping and interfaces to a blob of data from the network.
>
> template< typename native >
> struct net_word {
> char raw[ sizeof (native) ];
> operator native () const {
> native ret;
> COPY_OP( raw, raw + sizeof raw, reinterpret_cast< char * >( & ret ) );
> return ret;
> }
> net_word & operator = ( native const & value ) {
> COPY_OP( reinterpret_cast< char const * >( & value ), reinterpret_cast< char const * >( & value + 1 ), raw );
> return * this;
> }
> };
>
> Supposing the implementation aligns such a class the same as a char, is it safe to use it in the old-fashioned, unsafe C idiom:
>
> uint32_t datum = * (net_word< uint32_t > *) buf_ptr;

What's "buf_ptr"? Anyway, you seem to be aliasing a net_word
with a uint32_t, which seems to be undefined behavior according
to 3.10p10.

> Is it any safer to jump through a little hoop with placement new?
>
> uint32_t datum = * new( buf_ptr ) net_word< uint32_t >;

This destroys the previous contents of *buf_ptr, from a
specification point-of-view.
 
> Would any part of this mayhem be vulnerable to future semantic restrictions?

Which part of the future do you wish me to predict?

Jens

Received on 2014-03-19 22:30:19