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 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
|
#include <iostream>
#include <cstddef>
#include <type_traits>
#include <iomanip>
#define SHOW_MEMBER_OBJECT( S, m ) \
( std::cout << "member " #S "::" #m \
<< " type " << std::setw(13) << typeid(S::m).name() \
<< " size " << sizeof(S::m) \
<< " alignment " << alignof( decltype(S::m) ) \
<< " offset " << std::setw(2) << offsetof(S,m) << '\n' )
int main()
{
struct A
{
short s ; // size 2 alignment 2 offset 0
// pad 2 offset 2
int v ; // size 4 alignment 4 offset 4
char c ; // size 1 alignment 1 offset 8
// pad 7 offset 9
double d ; // size 8 alignment 8 offset 16
unsigned char u ; // size 1 alignment 1 offset 24
// pad 7 offset 25
}; // size 32
SHOW_MEMBER_OBJECT( A, s ) ;
SHOW_MEMBER_OBJECT( A, v ) ;
SHOW_MEMBER_OBJECT( A, c ) ;
SHOW_MEMBER_OBJECT( A, d ) ;
SHOW_MEMBER_OBJECT( A, u ) ;
std::cout << "sizeof(A) " << sizeof(A) << "\n---------------------\n\n" ;
struct B
{
short s ; // size 2 alignment 2 offset 0
char c ; // size 1 alignment 1 offset 2
unsigned char u ; // size 1 alignment 1 offset 3
int v ; // size 4 alignment 4 offset 4
double d ; // size 8 alignment 8 offset 8
}; // size 16
SHOW_MEMBER_OBJECT( B, s ) ;
SHOW_MEMBER_OBJECT( B, c ) ;
SHOW_MEMBER_OBJECT( B, u ) ;
SHOW_MEMBER_OBJECT( B, v ) ;
SHOW_MEMBER_OBJECT( B, d ) ;
std::cout << "sizeof(B) " << sizeof(B) << "\n---------------------\n\n" ;
#pragma pack(1)
struct C
{
short s ; // size 2 alignment 2(1) offset 0
int v ; // size 4 alignment 4(1) offset 2
char c ; // size 1 alignment 1 offset 6
double d ; // size 8 alignment 8(1) offset 7
unsigned char u ; // size 1 alignment 1 offset 15
}; // size 16
SHOW_MEMBER_OBJECT( C, s ) ;
SHOW_MEMBER_OBJECT( C, v ) ;
SHOW_MEMBER_OBJECT( C, c ) ;
SHOW_MEMBER_OBJECT( C, d ) ;
SHOW_MEMBER_OBJECT( C, u ) ;
std::cout << "sizeof(C) " << sizeof(C) << "\n---------------------\n\n" ;
#pragma pack(2)
struct D
{
short s ; // size 2 alignment 2 offset 0
int v ; // size 4 alignment 4(2) offset 2
char c ; // size 1 alignment 1 offset 6
// pad 1 offset 7
double d ; // size 8 alignment 8(2) offset 8
unsigned char u ; // size 1 alignment 1 offset 16
// pad 1 offset 17
}; // size 18
SHOW_MEMBER_OBJECT( D, s ) ;
SHOW_MEMBER_OBJECT( D, v ) ;
SHOW_MEMBER_OBJECT( D, c ) ;
SHOW_MEMBER_OBJECT( D, d ) ;
SHOW_MEMBER_OBJECT( D, u ) ;
std::cout << "sizeof(D) " << sizeof(D) << "\n---------------------\n\n" ;
}
|