[C++11 features] rvalue, lvalue, rvalue reference, lvalue reference

origin

C++ is an oop language, so it uses objects as the organizational structure. Some objects may not implement its assignment statement, and it does not need to be assigned. Then in the function, it needs to be used as an input parameter, and we must get its address. , that is, pointers, but pointer operations are risky, so we can use rvalue references.
In other words, we send the variable directly to the calling function without creating a temporary variable, which will also reduce memory overhead and time overhead caused by assignment

rvalue, lvalue

Avoid unnecessary copying, improve program performance
Avoid deep copying, optimize performance
&& may be an rvalue reference or an lvalue reference
& may also be an lvalue
lvalue, which can be assigned rvalue
, is temporary

lvalue reference, rvalue reference

  1. lvalue reference is an alias for lvalue
  2. Rvalue references require move semantics to use rvalues

move

The result of move must be an rvalue

a = MyString("Hello"); // move
MyString b = a; // copy
MyString c = std::move(a); // move, 将左值转为右值

forward

Forward reference, that is, the initial state in the current scope, such as the following code, is the type when t is converted into a parameter.
Note 1 calls the firstaaa
Note 2 calls the secondaaa
FirstaaaT a in T is essentially the lvalue of c
The secondaaaIn T a is essentially the rvalue of c

template <class T>
void aaa(T & t)
{
    
    
	T a = std::forward(T);
}

void aaa(T && t)
{
    
    
	T a = std::forward(T);
}
int c = 3;
aaa(c);						//1
aaa(std::move(c));	//2

How to determine lvalue or rvalue

Rational use of polymorphism to judge lvalue and rvalue

template <class T>
bool is_rightValue(T& t)
{
    
    
	return false; //这是左值
}
template <class T>
bool is_rightValue(T&& t)
{
    
    
	return true; //这是右值
}

Guess you like

Origin blog.csdn.net/qq_34954047/article/details/123636179