help-gplusplus
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: cast, reference and reinterpret_cast


From: Miles Bader
Subject: Re: cast, reference and reinterpret_cast
Date: Thu, 08 Feb 2007 08:28:42 +0900

"Frederic Mayot" <fred@mayot.net> 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.


reply via email to

[Prev in Thread] Current Thread [Next in Thread]