c++ - casting object addresses to char ptrs then using pointer math on them -
according effective c++, "casting object addresses char* pointers , using pointer arithemetic on them yields undefined behavior."
is true plain-old-data? example in template function wrote long ago print bits of object. works splendidly on x86, but... portable?
#include <iostream> template< typename type > void printbits( type data ) { unsigned char *c = reinterpret_cast<unsigned char *>(&data); std::size_t = sizeof(data); std::size_t b; while ( i>0 ) { i--; b=8; while ( b > 0 ) { b--; std::cout << ( ( c[i] & (1<<b) ) ? '1' : '0' ); } } std::cout << "\n"; } int main ( void ) { unsigned int f = 0xf0f0f0f0; printbits<unsigned int>( f ); return 0; }
it not portable. if stick fundamental types, there endianness , there sizeof, function print different results on big-endian machines, or on machines sizeof(int) 16 or 64. issue not pods fundamental types, structs may pod, too.
pod struct members may have internal paddings according implementation-defined alignment rules. if pass pod struct:
struct paddedpod { char c; int i; }
your code print contents of padding, too. , padding different on same compiler different pragmas , options.
on other side, maybe it's wanted.
so, it's not portable, it's not ub. there standard guarantees: can copy pods , array of char or unsigned char, , result of copying via char buffer hold original value. implies can safely traverse array, function safe. nobody guarantees array (or object representation) of objects same type , value same on different computers.
btw, couldn't find passage in effective c++. quote it, pls? say, if part of code contains lots of #ifdef thiscompilerversion
, makes sense go all-nonstandard , use hacks lead undefined behavior, work intended on compiler version pragmas , options. in sense, yes, casting char * leads ub.
Comments
Post a Comment