Summary of the usage of the C ++ sizeof Operator

Source: Internet
Author: User

In VC, sizeof has many usage and may cause some errors. Next, we will summarize the usage of sizeof based on the parameters following sizeof.

 


A. the parameter is of the data type or is A common variable:

For example, sizeof (int) and sizeof (long.

In this case, it should be noted that the results of different system systems or compilers may be different.

For example, the int type occupies 2 bytes in a 16-bit system and 4 bytes in a 32-bit system.

 


B. the parameter is an array or pointer:

Int a [50]; // sizeof (a) = 4*50 = 200; calculates the space occupied by the array.

Int * a = new int [50]; // sizeof (a) = 4; a is a pointer, and sizeof (a) is the pointer size. In a 32-bit system, of course, it occupies 4 bytes.

 


C. The parameter is a structure or class:

Sizeof applications process classes and structures in the same way. You need to consider byte alignment (in another article: C ++ custom struct and class memory alignment ). Note the following points:

First, static members in the structure or class do not affect the structure or class size, because the storage location of static variables is irrelevant to the instance address of the structure or class.

Second, the size of the structure or class (non-virtual) without member variables is 1, because each instance of the structure or class must have a unique address in the memory.

Third, the class that contains the virtual function or the class that inherits the virtual function must be counted as the four bytes occupied by the virtual table pointer.

 


The following is an example:

Class Test {int a; static double c}; // sizeof (Test) = 4.

Test * s; // sizeof (s) = 4, and s is a pointer.

Class test1 {}; // sizeof (test1) = 1;

Class test2 {virtual void print () {}}; // sizeof (test2) = 4;

 

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.