is portable aliasing possible in C++?

haynberg@yahoo.com haynberg@yahoo.com
Wed Sep 10 23:03:00 GMT 2014


> > So it would seem the answer is no, portable aliasing is not possible
> > in C++.  Though I wonder if it should be (with a new language
> > feature).
>
> In practice, a union is exactly that, and I've not heard of a compiler
> which doesn't do the right thing.  Given that it's explicitly legal in
> C11, I can't see any reason which C++ shouldn't simply adopt the same
> language.

I agree.  But in the union case, you're copying bytes.  If you don't perform 

a copy, for example:

struct msg {
  // ...
};
char *get_bytes();
msg *p = reinterpret_cast<msg*>(get_bytes());
if (p->i)
  // ...

Then there can't be a portable way to do this, because there's hardware that 

doesn't permit unaligned reads (e.g. where you'd get a SIGBUS).  So I guess 

I retract that "I wonder if" part :-)

Jay Haynberg



More information about the Gcc-help mailing list