[ub] data overlays: reinterpret_cast vs placement new
David Krauss
david_work at me.com
Tue Mar 18 06:06:48 CET 2014
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 *.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.open-std.org/pipermail/ub/attachments/20140318/a7dc4063/attachment.html
More information about the ub
mailing list