c++ - Are POD types always aligned? -
for example, if declare long variable, can assume aligned on "sizeof(long)" boundary? microsoft visual c++ online says so, standard behavior?
some more info:
a. possible explicitely create misaligned integer (*bar):
char foo[5]
int * bar = (int *)(&foo[1]);
b. apparently, #pragma pack() affects structures, classes, , unions.
c. msvc documentation states pod types aligned respective sizes (but or default, , standard behavior, don't know)
as others have mentioned, isn't part of standard , left compiler implement sees fit processor in question. example, vc implement different alignment requirements arm processor x86 processors.
microsoft vc implements called natural alignment size specified #pragma pack directive or /zp command line option. means that, example, pod type size smaller or equal 8 bytes aligned based on size. larger aligned on 8 byte boundary.
if important control alignment different processors , different compilers, can use packing size of 1 , pad structures.
#pragma pack(push) #pragma pack(1) struct example { short data1; // offset 0 short padding1; // offset 2 long data2; // offset 4 }; #pragma pack(pop)
in code, padding1
variable exists make sure data2 naturally aligned.
answer a:
yes, can cause misaligned data. on x86 processor, doesn't hurt @ all. on other processors, can result in crash or slow execution. example, alpha processor throw processor exception caught os. os inspect instruction , work needed handle misaligned data. execution continues. __unaligned
keyword can used in vc mark unaligned access non-x86 programs (i.e. ce).
Comments
Post a Comment