
On Thu, 11 Oct 2007 14:19:34 +0200, Roland Schwarz <roland.schwarz@chello.at> wrote:
First there was a typo: it should read operator T() const not operator T&() const
Zara wrote:
I may not work for PODs. It depends on the data alignment of the compiler, and the data alignment capabilities of the processor.
You are invoking the dreaded devils of Undefined Behaviour!
Of course I want to avoid this, but could you please be more specific?
Is it the static_cast<T>(*data)
that will cause troubles?
If so why?
Because not all processors may access words not aligned with the natural word boundary. This could result in some type of exception (depends on processor, OS, compiler...). OTOH, if you compile with 4-byte alignment, the cast *may* strip the lower bits of the pointer and give you rubbish instead of your value. This is UB, and should never be invoked.
Would it be better to use something like
operator T() const { T t = 0; for (unsigned n=0; n<sizeof(T); ++n) { t |= ((T)data[n])<<(8*n); } return t; }
yes, certainly. Just check if the endiannes is the right one, or if you must caculate the toal the oother way round. Best regrads, Zara