当前位置:网站首页>Clause 28: understanding reference folding

Clause 28: understanding reference folding

2022-06-13 04:55:00 CCSUZB

Consider the following code :

template<typename T>
void func(T &&parem);

Widget widgetFactory();	//  A function that returns an R-value 
Widget w;				//  Variable ( The left value )
func(w);				//  call func And pass in an lvalue ,T The derivation type of is Widget&
func(widgetFactor());	//  call func And pass in the right value ,T The derivation type of is Widget

The passed arguments are of type Widget, A left value , An R-value , This results in a template parameter T Different derivation results are obtained . A mechanism for determining whether universal references become lvalues or lvalues , It's also std::forward The mechanism that works .

stay C++ in “ Referenced references ” It's illegal. :

int x;
auto& & rx = x; // error ! A reference to a reference cannot be declared 

When an lvalue is passed to a universal reference, the following happens :

template<typename T>
void func(T &&parem);
func(w);

If you put T Type of derivation ( namely Widget &) Code instantiation template , The following results are obtained :

void func(Widget& && param);

The above is a reference to the reference . Due to universal citation param Is initialized by an lvalue , The derivation result type should be an lvalue reference , But what did the compiler do to get the following function signatures ?

 void func(Widget &param);

The answer is quotation folding , The rule is :

If any reference is an lvalue reference , Then the result is an lvalue reference , Otherwise, it is an R-value reference

Reference folding is to make std::forward The key to being able to work :

template<typename T>
void f(T &&fParam) {
    
	someFunc(std::forward<T>(fParam));	//  Will fParam Forward to somFunc
}

std::forward Task for : If and only if encoding T The information in indicates that the argument is passed an R-value , Yes fParam( The left value ) Implement cast to right value

Reference folding also happens auto Type generation of variables :

Widget w;
auto&& w1 = w;

initialization w1 Is an lvalue , therefore auto The type derivation result of is Widget &. stay w1 In the declaration Widget& Into the auto, The following code is generated for a long time :

Widget& && w1 = w;

When the reference is folded, it will become :

Widget & w1 = w;

The third case of reference folding is survival and use typedef And alias declaration :

template<typename T>
class Widget {
    
public:
	typedef T&& RvalueRefToT;
}

Suppose we instantiate with a sitting value reference :

Widget<int &> w;

stay Widget China and Israel int& Into the T The position of gets as follows :

typedef int & &&RvalueRefToT;

The reference is collapsed as :

typedef int& RvalueRefToTl;
原网站

版权声明
本文为[CCSUZB]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202280518034590.html