Analysis of the usage of sizeof operator in C + +

Source: Internet
Author: User

1. Overview
sizeof is an operator (operator) in C/s + + that returns the number of bytes of memory that an object or type occupies. The return value type is size_t and is defined in the header file stddef.h.

This is a value that relies on the compilation system, which is generally defined as typedef unsigned int size_t, but as a specification, the sizeof value of Char, signed char, and unsigned char is guaranteed to be 1, After all, char is the smallest data type that can be programmed.

The explanation on MSDN is:
The sizeof keyword gives the amount of storage, in bytes, associated with avariable or a type (including aggregate types). This keyword returns a value of type size_t.

2. Syntax
sizeof has three grammatical forms, as follows:
1) sizeof (object); sizeof (object);
2) sizeof (TYPE_NAME); sizeof (type);
3) sizeof object; sizeof object;

3. Basic types of sizeof
The basic data Type here refers to simple built-in data types such as short, int, long, float, double.
Because their memory size is system-dependent, the values may be different under different systems.

4. SizeOf of the structure
The structure of sizeof involves alignment issues.
Test code:

#includeusing namespace STD;intMain () {structa{CharAintb;};structBintbChar*p; };structC {};structB =intACharCDoubleD };structEChar* p; };cout<<"A:"<<sizeofA << Endl;cout<<"B:"<<sizeofB << Endl;cout<<"C:"<<sizeofC << Endl;cout<<"D:"<<sizeofD << Endl;cout<<"E:"<<sizeofE << Endl;return 0; }//Output Result:A:8B:8C:1D: -E:4

Why do I need byte alignment? The principle of computer composition teaches us that this helps to speed up the number of computers, otherwise we have to spend more instruction cycles. To do this, the compiler will handle the struct by default (as well as data variables elsewhere), so that the base data type of 2 (short, etc.) is located at an address divisible by 2, and the base data type (int, etc.) with a width of 4 is at an address divisible by 4, and so on. In this way, the number of bytes in the middle of the two may need to be added, so the sizeof value of the entire struct increases.
Byte alignment details are related to compiler implementations, but in general, three guidelines are met:
1) The first address of a struct variable can be divisible by the size of its widest base type member.
2) Each member of the struct is an integer multiple of the member size relative to the first address of the struct, and if necessary, the compiler adds padding bytes (internal adding) between the members.
3) The total size of the struct is an integer multiple of the size of the structure's widest base type member, and if necessary, the compiler adds padding bytes (trailing padding) after the last member.

Note: The sizeof value for an empty struct (without data members) is 1. Imagine how a "space-free" variable is addressed, and how the two different "empty struct" variables can be distinguished, so that the "empty struct" variable is stored so that the compiler can only allocate one byte of space for the placeholder.
5. The combined sizeof
Structs are listed sequentially in the memory organization, the consortium is overlapping, each member shares a piece of memory, so sizeof, the entire consortium, is the maximum value for each member sizeof.
Example:

#include <iostream>usingnamespacestdint main() {     union u     {         int a;         float b;         double c;         char d; };     cout"U: "sizeof u << endl;     return0; }

Result U:8

6. The sizeof array
The sizeof value of the array equals the number of bytes of memory consumed by the array.
Attention:
1) When a character array represents a string, its sizeof value evaluates to '/0 ' in.
2) When the array is a formal parameter, its sizeof value corresponds to the sizeof value of the pointer.

 #include <iostream>  using  namespace  STD ; int  Main () {char  a[     ]; cout  <<  "char a[10]"  << sizeof  (a) <<endl; cout  <<  "char n[]"  << sizeof  (n) << Endl;} Output: char  a[10 ] 10  char  n[] 4   

7. The sizeof pointer
Pointers are used to record the address of another object, so the memory size of the pointer is of course equal to the width of the address bus inside the computer.
On a 32-bit computer, the return value of a pointer variable must be 4.
The sizeof value of a pointer variable has no relation to the object that the pointer refers to.
8. sizeof for Functions
sizeof can also evaluate a function call, and the result is that the function returns the size of the value type, and the function is not called.
form of evaluation of functions: sizeof (function name (argument table))
Attention:
1) You cannot evaluate a function that has an empty return value type.
2) The function name cannot be evaluated.
3) In the case of a function with a parameter, when using sizeof, must write the argument table.

#include <iostream>using namespace STD;floatFUNCP (intAfloatb) {returnA + b; }intFUNCNP () {return 3; }voidFunc () {}intMain () {cout<<sizeof(FUNCP (3,0.4)) <<endl;//ok, a value of 4,sizeof (FUNCP (3,0.4)) equals sizeof (float) cout<<sizeof (FUNCNP ()) <<endl;//ok with a value of 4,sizeof ( FUNCNP ()) equals sizeof (int) cout<<sizeof (Func ()) <<endl; Error,sizeof cannot evaluate a function with a return value of NULL type [email protected] (FUNCNP) <<endl; Error,sizeof cannot evaluate the function name}

Output:
4
4
9. Class of sizeof
plays out!
There are many factors in C + + that affect the size of class objects, with the following factors:
1. The size of the non-static data member
2. Order of data members
3. Byte correction and alignment
4. Base class size
5. Whether there is a virtual function
6. Compiler used
7. Inheritance model, whether virtual inheritance

 #include <iostream>  using  namespace  STD ; class      A {private : float  iMem1; const      int  iMem2; static      int  iMem3; char  imem; }; int  Main () {cout  << " A: " << sizeof  (a) << Endl; return      0 ; }

Output:
A:12
Analysis: 12=sizeof (float) +sizeof (int) +sizeof (char) (aligned, so 4)
Thus, static members are not part of a class

#include <iostream>using namespace STD;classBCharCintInt1;intInt2;intILongL ShortS };classCintInt1;intInt2;intILongL ShortSCharC };intMain () {cout<<"B:"<<sizeof(B) << Endl;cout<<"C:"<<sizeof(C) << Endl;return 0; }

Output
B:24
C:20
The order of data members and the effect of alignment on the class size are visible from the above.

#include<iostream> usingnamespacestdclass B {     int iMem1;     intclass D:public B {     intint main() {     cout"D: "sizeof(D)<< endl;     return0; }

Output
D:12
Thus, the size of the subclass is affected by the size of the parent class.

#include <iostream>using namespace STD;classBase { Public:Virtual voidSomeFunction ();Private:intIamem; };classDerivedwithoutvirtual: PublicBase {Private:intIbmem; };classDerived: PublicBase {Virtual voidSomeotherfunction ();Private:intIbmem; };intMain () {cout<<"Derivedwithoutvirtual:"<<sizeof(derivedwithoutvirtual) << Endl;cout<<"Derived:"<<sizeof(Derived) << Endl;return 0; }

Derivedwithoutvirtual:12
Derived:12
Thus, the virtual function in the class will increase by 4 bytes. It should be noted, however, that if the parent class has virtual functions, the subclasses also have virtual functions, and the size of the subclasses does not include the size of the virtual function of the parent class!!

#include <iostream>using namespace STD;classAbase {intImem; };classBbase: Public VirtualAbase {intIbmem; };classCBase: Public VirtualAbase {intIbmem; };classAbcderived: PublicBbase, PublicCBase {intImem; };intMain () {cout<<"Abase:"<<sizeof(abase) << Endl;cout<<"Bbase:"<<sizeof(bbase) << Endl;cout<<"CBase:"<<sizeof(CBase) << Endl;cout<<"abcderived:"<<sizeof(abcderived) << Endl;return 0; }

Abase:4
Bbase:12
Cbase:12
Abcderived:24
Thus:
the size of the abcderived is 24, not the sizeof (bbase + CBase + int member))
The size is 24 because it has only one virtual base class pointer;

In Summary:
1. Usually, in the inheritance of virtual function, it is not the size of virtual function in calculating base class, so there is only one virtual function table in a class.
2. Virtual inheritance is relatively more complex, the problem of virtual inheritance is mainly, the current base class size, plus now the size of the class, but also to add a virtual pointer, this virtual pointer to the virtual function, so the equivalent of additional 4, but also to follow the first condition, a function can only have a virtual pointer, A virtual pointer table, so in the calculation to note that each function has only one of its own virtual pointer!

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Analysis of the usage of sizeof operator in C + +

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.