The following 5 columns are for C + + and do not involve sizeof byte alignment and basic data types that are specific to C + + and are targeted at 32-bit machines
Using sizeof in C + + is much more complicated than C, because there are static variables in C + + classes, virtual functions, and inheritance, derivation, and so on. sizeof is a single order operator in C language, such as other operators in C + + 、--. It's not a function. The sizeof operator gives the storage size of its operands in bytes.
There are three types of sizeof used: sizeof (var_name) or sizeof var_name or sizeof (Var_type).
"Example 1": (Liezi ignores constructs and destructors)
Copy Code code as follows:
class A
{
Public:
void Hello () {}
};
sizeof (A) = 1;
Definitely not zero. To give a counter example, if it is 0, declare a Class A a[10] object array, and each object occupies zero space, then there is no way to distinguish a[0],a[1] ... Up.
Because A is an empty class, the byte is 1 to differentiate between two different objects, or as a placeholder, the address of the byte is the address of the object. But the 1 here is not absolute, it's just a compiler setting.
"Example 2":
Copy Code code as follows:
class B
{
Public:
void Hello () {}
static int i;
};
sizeof (B) = 1;
Because static variables are shared in a class, space is allocated in the static area, space is allocated at compile time, and no class memory is occupied.
"Example 3":
Copy Code code as follows:
CLASSC
{
Public:
virtual void Hello () {}
};
sizeof (C) = 4;
Class B has a virtual function, the corresponding will have a virtual table pointer exists, accounting for 4 bytes, exactly a pointer space. Also, if you have more than one virtual function or if more than one class inherits the C class, the virtual function also takes up only 4 bytes, such as "Example 4":
"Example 4":
Copy Code code as follows:
class D:public C
{
Public:
virtual void World () {}
virtual void Nihao () {}
};
sizeof (D) = 4;
"Example 5":
Copy Code code as follows:
Class E
{
Public
virtual void Hello () {}
virtual void World () {}
Staticint i;
static int J;
int k;
};
sizeof (E) = 8;
I hope it will be of some help to you.