1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
|
#include <iostream>
#include <cstddef>
struct B
{
int b ;
int other ;
};
struct C
{
int c ;
int other ;
};
struct D
{
int d ;
int other ;
};
union A
{
int a ;
B bb ;
C cc ;
D dd ;
};
int main()
{
// standard-layout union (all non-static data members are at an offset of zero)
static_assert( offsetof(A,a) == 0, "must be at a zero offset" ) ;
static_assert( offsetof(A,bb) == 0, "must be at a zero offset" ) ;
static_assert( offsetof(A,cc) == 0, "must be at a zero offset" ) ;
static_assert( offsetof(A,dd) == 0, "must be at a zero offset" ) ;
// standard-layout struct (first non-static data member must be at an offset of zero)
static_assert( offsetof(B,b) == 0, "must be at a zero offset" ) ;
static_assert( offsetof(D,d) == 0, "must be at a zero offset" ) ;
static_assert( offsetof(C,c) == 0, "must be at a zero offset" ) ;
// standard-layout struct (the second non-static data member must be at an offset greater than zero)
static_assert( offsetof(B,other) > 0, "must be at an offset greater than zero" ) ;
static_assert( offsetof(C,other) > 0, "must be at an offset greater than zero" ) ;
static_assert( offsetof(D,other) > 0, "must be at an offset greater than zero" ) ;
constexpr A obj {} ;
static_assert( &obj.a == &(obj.bb.b), "must be at the same address" ) ;
static_assert( &obj.bb.b == &(obj.cc.c), "must be at the same address" ) ;
static_assert( &obj.cc.c == &(obj.dd.d), "must be at the same address" ) ;
A aa { 72 };
std::cout << aa.a << ' ' << aa.bb.b << ' ' << aa.cc.c << ' ' << aa.dd.d << '\n' ; // 72 72 72 72
aa.bb.b = 34 ;
std::cout << aa.a << ' ' << aa.bb.b << ' ' << aa.cc.c << ' ' << aa.dd.d << '\n' ; // 34 34 34 34
aa.dd.d = 99 ;
std::cout << aa.a << ' ' << aa.bb.b << ' ' << aa.cc.c << ' ' << aa.dd.d << '\n' ; // 99 99 99 99
}
|