code, software architect, articles and novels. 代码,软件架构,博客和小说
Sizeof in C++
Posted onEdited onWord count in article: 1.8kReading time ≈2 mins.
I use c++ in linux which is gcc version 4.4.1 (Ubuntu 4.4.1-4ubuntu9).
I considered that c++ memory alignment is like the following:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
// pseudo-code of memory alignment remove_all_static_varibles(); int max= 0; foreach(element in struct) find_the_max_memory_used(element,&max); int align = max > default? default: max; // if max memory used for element is larger than the default, use default. int memory = sum(memory_used(elements));
vc++ use #pragma_pack(n) set the default.if there are three char in a struct, like:
1 2 3 4 5 6
typedef struct{ char a; char b; char c; }X; sizeof(X); // it will be 3
1 2 3 4 5 6 7 8 9 10 11 12 13
typedef struct{ char a; short b;
}Y; sizeof(Y); // here will be 4
typedef struct{ char a; int b; }Z;
sizeof(Z); // here will be 8
1 2 3 4 5 6 7 8
typedef struct{ double a; char b; }W; sizeof(W); // it will be 12, the align is 4 // when the max memory used is larger // than 4, it will be 4
if the class or struct is empty, sizeof(it) will be 1.
But if there are static varibles in classes or structs, you can remove it!. like:
1 2 3 4 5
class A{ static int a;
}; sizeof(A); // it will be 1
in class there will be many class functions. But A class is thought as A struct and many functions set. sizeof(A class) will compute the size of struct.