Всем привет!
Как вы думаете, какой размер объекта, в котором одна переменная bool, и одна переменная uint16 (и больше нет других переменных)? Я думал 3 байта. Оказывается 4.
После экспериментов было выяснено, что все объекты выравниваются по размеру наиболее «тяжелого» типа, но не более 4 байт (думаю, зависит от платформы, у меня 32 бит).
Вопросы:
1. Это в нормально или это undefined behaviour и особенность gcc?
2. Как это отключить, и желательно в исходнике (не ключем компилятора)?
Спасибо.
P. S. Эксперимент:
#include<cstdint>
#include<iostream>
#include<iomanip>
class C01{
bool a;
};
class C02{
bool a;
bool b;
};
class C03{
bool a;
bool b;
bool c;
};
class C04{
uint16_t a;
};
class C05{
uint16_t a;
bool b;
};
class C06{
uint16_t a;
bool b;
bool c;
};
class C07{
uint16_t a;
bool b;
bool c;
bool d;
};
class C08{
uint32_t a;
};
class C09{
uint32_t a;
uint16_t b;
};
class C10{
uint32_t a;
uint16_t b;
uint16_t c;
};
class C11{
uint32_t a;
uint16_t b;
uint16_t c;
bool d;
};
class C12{
uint64_t a;
bool d;
};
class C13{
uint64_t a;
uint16_t b;
};
class C14{
uint64_t a;
uint16_t b;
uint16_t c;
bool d;
};
int main()
{
std::cout << "Bigget type: bool" << std::endl;
std::cout << "sizeof(C01)=" << sizeof(C01) << std::endl;
std::cout << "sizeof(C02)=" << sizeof(C02) << std::endl;
std::cout << "sizeof(C03)=" << sizeof(C03) << std::endl;
std::cout << "Bigget type: uint16_t" << std::endl;
std::cout << "sizeof(C04)=" << sizeof(C04) << std::endl;
std::cout << "sizeof(C05)=" << sizeof(C05) << std::endl;
std::cout << "sizeof(C06)=" << sizeof(C06) << std::endl;
std::cout << "sizeof(C07)=" << sizeof(C07) << std::endl;
std::cout << "Bigget type: uint32_t" << std::endl;
std::cout << "sizeof(C08)=" << sizeof(C08) << std::endl;
std::cout << "sizeof(C09)=" << sizeof(C09) << std::endl;
std::cout << "sizeof(C10)=" << sizeof(C10) << std::endl;
std::cout << "sizeof(C11)=" << sizeof(C11) << std::endl;
std::cout << "Bigget type: uint64_t" << std::endl;
std::cout << "sizeof(C12)=" << sizeof(C12) << std::endl;
std::cout << "sizeof(C13)=" << sizeof(C13) << std::endl;
std::cout << "sizeof(C14)=" << sizeof(C14) << std::endl;
return 0;
};
$ g++ -std=c++11 type_test.cpp -o type_test && ./type_test
Bigget type: bool
sizeof(C01)=1
sizeof(C02)=2
sizeof(C03)=3
Bigget type: uint16_t
sizeof(C04)=2
sizeof(C05)=4
sizeof(C06)=4
sizeof(C07)=6
Bigget type: uint32_t
sizeof(C08)=4
sizeof(C09)=8
sizeof(C10)=8
sizeof(C11)=12
Bigget type: uint64_t
sizeof(C12)=12
sizeof(C13)=12
sizeof(C14)=16
P. P. S. static_assert
рулит!