Usage notes for reference types

Source: Internet
Author: User

The reference type is defined by the type identifier and an address fetch operator. The reference must be initialized.

See the following initialization:

Double dval = 3.14159;

Extern int F ();

Int & ir1 = 1024; // Error

Int & ir2 = dval; // Error

Int & ir3 = f (); // Error

The above three references will cause compilation errors during initialization.

In fact, the reference is stored inside an object address, which is the alias of the object. For unaddressable values, such as text constants and different types of objects, the compiler must generate a temporary object to implement the reference. The reference actually points to this object, but the user cannot access it. for example, we wrote:

Double dval = 3.14159;

Int & ir2 = dval;

Because type conversion is required, the compiler converts it:

Int temp = dval; Int & ir2 = temp; // If you assign a new value to ir2 at this time, the change is temp, not dval.

// While temp is unaddressable, it is not intended for users.

Therefore, in this case, we need to reference const because they are read-only and do not allow non-const references to point to objects or values that require temporary objects. in addition, the return value of Int & ir3 = f () and F () functions is also a temporary value and cannot be used to initialize non-const type references.

The correct modification is as follows:

Const Int & ir1 = 1024; // OK

Const Int & ir2 = dval; // OK

Const Int & ir3 = f (); // OK

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.