* Victor Bazarov:
andrew said:
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).
On the other hand, the only harm it can do inside a sizeof is to make
som rather dumb compiler choke on the expression, and it's an old idiom.
On the third & gripping hand, at the technical level, where we don't
care about how a better design might make the need go away, this is
really a job for the Unimplemented Fake Function, the UFF,
foo& foon();
char samesizeAsFoox[ sizeof( foon().x ) ];