The purpose of the new feature
The right value reference (Rvalue referene) is a new feature introduced in the new C + + standard (c++11, 11 for 2011), which implements the transfer semantics (move sementics) and precise delivery (Perfect forwarding). Its main purposes are two aspects:
Eliminates unnecessary copy of objects when two objects are interacting, saves operational storage resources, and improves efficiency.
can define generic functions more concisely and explicitly.
Definition of left value and right value
All expressions and variables in C + + (including C) are either left or right. The common definition of a left value is a temporary object, an object that can be used in more than one statement. All variables satisfy this definition and can be used in more than one code, both of which are left values. The right value refers to temporary objects that are valid only in the current statement. Take a look at the following examples:
A simple assignment statement
such as: int i = 0;
In this statement, I is the left value, 0 is a temporary value, is the right value. In the following code, I can be referenced, 0 is not allowed. Immediate numbers are the right values.
The right value can also appear to the left of an assignment expression, but it cannot be an assigned object because the right value is only valid in the current statement, and the assignment is meaningless.
For example: ((i>0) i:j) = 1;
In this example, 0 appears as the right value on the left side of the "=". But the assignment object is either I or J, and the value is left.
Before c++11, the right value cannot be referenced, and the maximum is to bind a right value with a constant reference, such as:
const int &a = 1;
In this case, the right value cannot be modified. But actually the right value can be modified, such as:
T (). Set (). get ();
T is a class, and set is a function that assigns a value to a variable in T, and a get is used to take out the value of the variable. In this sentence, T () generates a temporary object, which is the right value, the set () modifies the value of the variable, and the right value is modified.
Since the right value can be modified, then the right value reference can be implemented. The right value reference can easily solve the problems in the actual project and realize the very attractive solution.
Syntax symbols for left and right values
The declaration symbol for the left value is "&", and for the value to be distinguished from the left, the declaration of the right value is "&&".
Sample programs:
void Process_value (int& i) {
std::cout << "LValue processed:" << i << Std::endl;
}
void Process_value (int&& i) {
std::cout << "RValue processed:" << i << Std::endl;
}
int main () {
int a = 0;
Process_value (a);
Process_value (1);
}