In C ++ programming languages, constant reference is a very important application technique. In this article, we will introduce in detail the application methods of C ++ constant reference. I believe you can learn a lot from it.
- Basic Content of C ++ Singleton Mode
- Analysis of related methods for creating Web services in C ++
- How to initialize the C ++ Constructor
- Skills related to C ++ identifier naming rules
- Basic concepts of C ++ function templates
If a constant is referenced, the compiler first creates a temporary variable and then places the value of the constant into the temporary variable. The referenced operation is the operation on the temporary variable. The C ++ constant reference can be initialized with any other reference, but cannot be changed.
There are two points worth noting about the initialization of the reference:
1) there is no problem when the initialization value is a left value and the address can be obtained;
2) When the initialization value is not a left value, only one const T & constant reference can be assigned a value. In addition, this assignment has a process:
First, the value is implicitly converted to the type T, and then the conversion result is stored in a temporary object. Finally, this temporary object is used to initialize the reference variable.
Example:
- Double & dr = 1; // error: The left value is required.
- Const double & cdr = 1; // OK
The actual process of the second sentence is as follows:
- double temp = double(1);
- const double& cdr = temp;
When using function parameters:
- // bc_temp_objects_not_bound_to_nonconst_ref.cpp
- // compile with: /EHsc
- #include "iostream"
- using namespace std;
- class C {};
- void f(C & c) { cout << "C&" << endl; }
- void f(C const & c) { cout << "C const &" << endl; }
- int main() {
- f(C());
- }
Result:
C const &
More directly, use the basic types:
- #include <iostream>
- using namespace std;
- void display(int const &ref) {cout<<ref<<'\n';}
- int main()
- {
- int i=1;
- display(i);
- int const anotheri=2;
- display(anotheri);
- display(2);
- display(1+2);
- display(static_cast<int>(3.14159));
- }
Return a local object from the function through the C ++ constant reference:
Generally, it is incorrect to return a local object reference from a function:
- T & my_op ( void )
- {
- T t;
- return t;
- } // The T object t got destroyed here so the
returned reference is not valid anymore.
Special case: a common reference is returned.
- const T & my_op ( void )
- {
- T t;
- return t;
- }
- const T & my_t_obj = my_op ();
In this case, the local variable t will not be directly analyzed, but will be retained until the end of the lifecycle of my_t_obj.
In short, a temporary variable can be referenced in the C ++ constant reference syntax. This method makes sense when using references as function parameters and returning local variables. In my opinion, constant reference is mainly used for function parameters or to ensure that the original variables are not modified.