Re: Valid C++?
Alf P. Steinbach wrote:
* Victor Bazarov:
andrew queisser wrote:
Is this code below valid C++? I'd like to use this construct but I'm
not sure if it'll be portable.
struct foo
{
char x[128];
};
struct bar
{
char sameSizeAsFooX[ sizeof ((foo *)0)->x ];
It is OK, I guess. Seems rather dangerous though, like dereferencing
a null pointer. Perhaps it would be less scary to do
char sameSizeAsFoox[ sizeof foo().x ];
(although it does require for 'foo' to be default-constructible while
your solution does not).
};
On the one hand, dereferencing a null-pointer is formally UB no matter
which context (except in a typeid expression).
Actually, the exception covers not only typeid, but also sizeof:
"An expression is potentially evaluated unless either it is the operand of
the sizeof operator (5.3.3), or it is the operand of the typeid operator
and does not designate an lvalue of polymorphic class type (5.2.8)."