I use c++ in linux which …">

帐前卒专栏

Without software, we are nothing.

Sizeof in C++

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));

if(memory%align != 0)
// here will execute alignment!
{
    memory = (memory/align + 1 )*align;
}
if(memory == 0)
    memory = 1;
return memory;

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.

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
class ZZ{
    public:
        ZZ(){
            int a = 3;
            cout << "I am ZZ"<<endl;
            cout << a<<endl;
        }
        ~ZZ(){

        }
    int c;
};
sizeof(ZZ); // will be 4;
/* it is like a struct and two member functions.
struct ZZ{
  int c;
};

ZZ@ZZ() is name mingling
ZZ@ZZ(){
  int a = 3;
        cout << "I am ZZ"<<endl;
        cout << a<<endl;
}
ZZ@~ZZ(){

}
*/

but when we meet the virtual member functions and virtual derived class, it will be different.

Comments