Computes the bytes occupied by the C + + class (that is, sizeof)

Source: Internet
Author: User

In a class, if there is nothing, the class consumes 1 bytes, and once there are other space-occupying members in the class, the 1 bytes are not counted, such as a class with only one int that takes 4 bytes instead of 5 bytes. If there is only a member function, it is still only 1 bytes, because the class function does not occupy space. virtual function Because there is a virtual function table, requires 4 bytes, the data member object if the pointer is 4 bytes, note that there is byte alignment, if it is 13 bytes, it is rounded up to 16 bytes of space. Need to note:

1 to find out if there is a virtual function table, +4
2 static member variables belong to the class domain and are not counted into the object +0
3 God horse members do not have a class, or only member functions +1
4 Note the Alignment rule

Example:

classctest{ Public: CTest (): M_chdata (' \0'), M_ndata (0)        {        }        Virtual voidMem_fun () {}Private:        CharM_chdata; intM_ndata; Static CharS_chdata;};CharCtest::s_chdata= ' \0’;
(1) What is the value of sizeof (CTest) If you press 4 bytes? (2) What is the value of sizeof (CTest) If you press 1 bytes? Answers: 12 and 9

Computes the bytes occupied by the C + + class (that is, sizeof)

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.