Suppose there is non-POD struct below, is the alignment taken effect? If not, what would be expected?
struct S1
{
string s;
int32_t i;
double d;
} __attribute__ ((aligned (64)));
EDIT: the output of the sample code below is 64 even s is set to a long string.
int main(int argc,char *argv[])
{
S1 s1;
s1.s = "123451111111111111111111111111111111111111111111111111111111111111111111111111";
s1.i = 100;
s1.d = 20.123;
printf("%ld\n", sizeof(s1));
return 1;
}
Yes, the alignment takes effect in GCC.
Example code:
Output:
Also: You have observed that
S1is non-POD. Note thatstd::stringis allowed to store its data externally (it usually does so because the data can be of arbitrary length, so a memory buffer must be allocated dynamically).Remember that
sizeofis only calculated during compilation, it can’t depend on runtime values. Specifically, you can’t ever query a size of dynamically allocated memory this way.Also remember that every element in an array is always of the same type, so of the same size too.