General use of a reference to a constant (reference to const) (reproduced)

Source: Internet
Author: User

If you are referencing a constant, the compiler first establishes a temporary variable, and then the value of that constant is placed in a temporary variable, and the action on that reference is the operation on that temporary variable. A C + + constant reference can be initialized with any other reference, but it cannot be changed.

There are two points worth noting about the initialization of references:

(1) When the initial value is an lvalue (can get address), there is no problem;

(2) When the initial value is not an lvalue, only one const t& (constant reference) can be assigned. And there is a process for this assignment:

First, the value is implicitly converted to type T, and then the result is stored in a temporary object, which is then initialized with the temporary object to initialize the reference variable.

Returns a local object from a function through a C + + constant reference:

It is not common to return a reference to a local object from a function:

1 void )   2{   3    t t;    4     return t;    5 // The T-Object T got destroyed here and the returned reference is not valid anymore  .

Special case: Returns a common reference

Const void )   {       T t;        return t;   }    Const T & my_t_obj = My_op ();  

In this case, the local variable t will not be destroyed directly, but will remain until the end of the My_t_obj life cycle.

In summary, a C + + constant Reference syntax can reference a temporary variable. This method makes sense when using references as function arguments and returning local variables. For the time being, the constant reference is used primarily as a function parameter or as a guarantee that the original variable is not modified.

General use of a reference to a constant (reference to const) (reproduced)

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.