Introduction to c ++ const reference and non-const reference

Source: Internet
Author: User

A const reference is a reference to a const object. Copy codeThe Code is as follows: const int I = 10;
Const int & ref = I;

You can read the ref but cannot modify it. This makes sense, because I itself cannot be modified, and of course it cannot be modified through ref. Therefore, it is invalid to assign the const variable to a non-const reference.Copy codeThe Code is as follows: int & ref1 = I; // error: nonconst reference to a const object

A non-const reference is a reference to a non-const type variable.
Const references can be initialized to different types of objects or right values (such as literal constants), but non-const references cannot.Copy codeThe Code is as follows: // legal for const references only
Int I = 10;
Const int & ref = 42;
Const int & ref1 = r + I;
Double d = 3.14;
Const int & ref2 = d;

Take binding to different types of ref2 as an example to explain the cause. The compiler will convert the ref2-related Code as follows:Copy codeThe Code is as follows: int temp = d;
Const int & ref2 = temp; // bind ref2 to temporary

Ref2 is actually bound to a temporary variable. If ref2 is not a const, you can modify the value of d by modifying ref2, but actually d will not change. To avoid this problem, ref2 can only be a const.

Non-const references can only be bound to objects of the same type as the reference. const references can be bound to objects of different but related types or to the right value.

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.