Alex Rivera | Logout

C99 strict aliasing rules in C++ (GCC)

Asked 2010-05-05T06:25:53.177
20

As far as I understand, GCC supports all of its C99 features in C++. But how is C99 strict aliasing handled in C++ code?

I know that casting with C casts between unrelated types is not strict-aliasing-safe and may generate incorrect code, but what about C++? Since strict aliasing is not part of C++ standard (is that correct?), GCC must be specifying the semantics itself.

I figure const_cast and static_cast cast between related types, hence they are safe, while reinterpret_cast can break strict aliasing rules.

Is this a correct understanding?

Edit
Report

1 Answer

4

static_cast can break aliasing rules too, because the compiler is trusting you to ensure that the target type is related to the actual runtime type of the object. Consider:

extern void f(double*, int*); // compiler may optimize assuming that arguments don't overlap
double d;
void* pv = &d;
int* pi = static_cast<int*>(pv);
f(&d, pi); // assumption is violated
answered 2010-05-05T06:30:52.753

Your Answer