C + + Learning Note----memory model for 2.4 C + + objects

Source: Internet
Author: User

Reprinted from: http://c.biancheng.NET/cpp/biancheng/view/2995.html Click to open link

When an object is created, the compiler allocates memory space for each object, including member variables and member functions.

The intuitive understanding is that if you define 10 objects, you should allocate memory space for the variables and functions of these 10 objects, as shown in:


Although each object has a different member variable, the code for the member function is the same, and the memory model above saves 10 copies of the same code fragment, wasting a lot of space.

in fact, the compiler stores member variables and member functions separately: allocates memory for each object's member variables, but all objects share the same segment function code. as shown in the following:


Take a look at one of the following examples:

[CPP]View PlainCopy
  1. #include <iostream>
  2. Using namespace std;
  3. Class demo{
  4. Public
  5. int A;
  6. float B;
  7. void display ();
  8. };
  9. void Demo::d isplay () {
  10. cout<<"a=" <<a<<", b=" <<b<<endl;
  11. }
  12. int main () {
  13. Demo obj;
  14. OBJ.A = 1;
  15. OBJ.B = 2;
  16. Obj.display ();
  17. return 0;
  18. }


Obj is both an object and a local variable in the main function, and the type is Demo, which allocates memory on the stack, just like a normal variable defined by int, char, and so on.

Assuming that the starting address of obj is 0X1000, then its memory distribution is as follows:


Both A and B are of type int, occupy 4 bytes of memory, and are arranged sequentially in the order in which they are declared, so the Obj object occupies a total of 8 bytes of memory. The reader can use the sizeof(obj) Statement Pro-Test.

The size of an object is only affected by member variables, and is not related to member functions. The member function allocates memory in the code area , not in the stack area.

C + + Learning Note----memory model for 2.4 C + + objects

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.