"Frederic Mayot" <[EMAIL PROTECTED]> writes: > Can someone explain me why the following line of code does not compile > the same way on g++ 3.4.6 and g++ 4.1.1 in 64 bits: > (char*&)p += sizeof(A); > AND > p = reinterpret_cast<A*>(reinterpret_cast<char*>(p) + sizeof(A));
I can't give a formal explanation, but I can offer a clue which might help: try compiling with the "-Wall" option; you'll get the following warning: x.cc:11: warning: dereferencing type-punned pointer will break strict-aliasing rules Then try compiling using the option "-fno-strict-aliasing"; this will get rid of the warning, and will also make the compiler generate equivalent code for both variants. The generated code isn't precisely the same -- the compiler in fact will generate worse-but-equivalent code for your 2nd variant. This tells you that (1) your first variant is breaking an assumption made by gcc's optimizer, which presumably is causing the optimization to produce bogus code, and (2) the optimization in question ("strict-aliasing") is a useful optimization, as it apparently helped the compiler produced better code for the 2nd variant. Is the 1st variant even legal/portable C++?? It seems much dodgier than the 2nd -- and in fact, wouldn't something using static_cast via void* be even safer (though annoyingly verbose)? e.g., if "sc" is static_cast: p = sc<A*>(sc<void*>(sc<char*>(sc<void*>(p)) + OFFS)) [My reasoning being that static_cast gives the compiler a chance to perform any necessary conversions in pointer format on odd architectures.] -Miles -- Quidquid latine dictum sit, altum viditur. _______________________________________________ help-gplusplus mailing list help-gplusplus@gnu.org http://lists.gnu.org/mailman/listinfo/help-gplusplus