C++ Logo

sg12

Advanced search

[ub] data overlays: reinterpret_cast vs placement new

From: David Krauss <david_work_at_[hidden]>
Date: Tue, 18 Mar 2014 13:06:48 +0800
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;

Is it any safer to jump through a little hoop with placement new?

uint32_t datum = * new( buf_ptr ) net_word< uint32_t >;

Would any part of this mayhem be vulnerable to future semantic restrictions?

For the sake of argument, assume that the underlying memory came straight from malloc (and the NIC) and it’s never been assigned a dynamic type, or referenced in any way besides char *.


Received on 2014-03-18 06:07:15