Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a struct of one element compatible with the element itself?

Tags:

c++

c++11

If I have the following struct:

struct Foo { int a; };

Is the code bellow conforming with the C++ Standard? I mean, can't it generate an "Undefined Behavior"?

Foo foo;
int ifoo;

foo = *reinterpret_cast<Foo*>(&ifoo);

void bar(int value);

bar(*reinterpret_cast<int*>(&foo));

auto fptr = static_cast<void(*)(...)>(&bar);
fptr(foo);
like image 507
Guilherme Bernal Avatar asked Jan 23 '12 11:01

Guilherme Bernal


1 Answers

9.2/20 in N3290 says

A pointer to a standard-layout struct object, suitably converted using a reinterpret_cast, points to its initial member (or if that member is a bit-field, then to the unit in which it resides) and vice versa.

And your Foo is a standard-layout class.

So your second cast is correct.

I see no guarantee that the first one is correct (and I've used architecture where a char had weaker alignment restriction than a struct containing just a char, on such an architecture, it would be problematic). What the standard guarantee is that if you have a pointer to int which really point to the first element of a struct, you can reinterpret_cast it back to pointer to the struct.

Likewise, I see nothing which would make your third one defined if it was a reinterpret_cast (I'm pretty sure that some ABI use different convention to pass structs and basic types, so it is highly suspicious and I'd need a clear mention in the standard to accept it) and I'm quite sure that nothing allow static_cast between pointers to functions.

like image 140
AProgrammer Avatar answered Nov 10 '22 12:11

AProgrammer