Temporary of Type 'int'

Source: Internet
Author: User

 

Run the following statement and you will get an error:

Invalid initialization of non-const reference of Type 'int & 'from a temporary of Type 'int'

 

 

int &z = 12;

 

12 This value has no name, so it is temporary (temporary). You cannot assign a temporary variable to a reference (& Modified) type.

 

However, you can assign the temporary value to the reference type modified by const. Why?

 

Foreign websites have heated discussions on this:

Http://stackoverflow.com/questions/8293426/error-invalid-initialization-of-non-const-reference-of-type-int-from-an-rval? RQ = 1

 

 

# Include <stdio. h> template <class T> T returnself (T & V) {return V;} template <class T> int compare (const T & V1, const T & V2) {If (V1 <V2) Return-1; if (V1> V2) return 1; return 0;} int main () {int I = 1; float J = 2.0f; double K = 3.0; printf ("I is: % d \ n", returnself (I); printf ("J is: % F \ n ", returnself (j); printf ("K is: % F \ n", returnself (k); compare ("hi", "88 "); // "hi" and "hi1" are different styles. in T ret = compare (I, 10); // can't set temporary value to reference. printf ("compare I with 10, the result is: % d", RET );}~
Related Article

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.