The underlying implementation referenced in C + +

Source: Internet
Author: User

To study the underlying implementation of the reference in C + +, write a small code to verify the rationale.

The reference is the alias of a variable, and in the end will it request memory space for the reference? If you apply for space, the space is stored, the following code is the main solution to this question.

The code is as follows, see code comments in detail

1#include <iostream>2#include <string>3#include <vector>4#include <algorithm>5 using namespacestd;6 7 classTest8 {9  Public:Ten     intVal; One     int&Ref_val; ATest (): Val (0xFFFFFFFF), Ref_val (Val) -     { -     } the }; -  - intMain () - { + Test obj; -cout <<sizeof(obj) <<endl;//in VS2008, the result of Win7 32 bit is 8, indicating that the reference is also a memory space +cout << &obj<<endl;//0x001bfa28 Acout << & (Obj.val) <<endl;//0x001bfa28 atcout << & (Obj.ref_val) <<endl;//0x001bfa28 -  -     intI=0x01010101; -     int*ptr = &i;// -cout << &i<<Endl; -cout << ptr <<Endl; incout <<& (*ptr) <<Endl; -  to     return 0; +}

Through the output, the following results can be obtained

1, the reference in memory will also allocate space, the space in which things are referred to the variable address, so the reference can be seen as a constant pointer ptr;

2, the reference to take the address operation, in fact, is the address of the referenced variable, the compiler will interpret the reference address as & (*PTR) address, the 29th line in the code confirms this statement

Run results

Memory results when debugging (memory results can be seen as small end little-ending mode)

The underlying implementation referenced in C + +

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.