🐭 右值引用与通用引用
右值引用:
现代 C++ 新引入的一种引用类型,大概语法形式为 T&&,右值引用只能绑定到一个右值,一般与 std::move 一起工作。
通用引用:
一种比较特殊的引用类型,大概语法形式也是 T&&,它会根据初始化物的类型进行类型推导,可以绑定到一个左值也可以绑定到一个右值,一般与 std::forward 一起工作,也叫转发引用。
代码示例 :
#include <iostream>struct X {};// T&& as rvalue reference// to identify objects that may be moved fromvoid func1(X &&x){}; // rvalue referencetemplate <typename T> void func2(std::vector<T> &&arg); // rvalue referencetemplate <typename T> void func3(const T &&arg); // rvalue referenceX &&x1 = X{}; // rvalue reference// T&& as a universal (forwarding) reference// must be type deduction, arise in two contexts// 1. for function template parameters// 2. auto&& declarations, including lambda casetemplate <typename T> void func3(T &&arg); // forwarding referenceauto &&x2 = x1; // universal reference// auto&& in lambda as forwarding reference// func is a universal reference that can be bound to any callable object,// args is zero or more universal references that can be bound to any number// of objects of arbitrary typesdecltype(auto) funcInvocation = [](auto &&func, auto &&... args) {return std::forward<decltype(func)>(func)(std::forward<decltype(args)>(args)...);};// T&& as a universal (forwarding) reference// can bind to lvalue and rvalue (can bind to virtually anything)// 1. bind to lvalue forms a lvalue reference// 2. bind to rvalue forms a rvalue referencetemplate <typename T, std::enable_if_t<std::is_same_v<std::decay_t<T>, X>, int> = 0>void func4(T &&arg) {if constexpr (std::is_same_v<decltype(arg), X &>) {std::cout << "arg = X&\n";} else if constexpr (std::is_same_v<decltype(arg), const X &>) {std::cout << "arg = const X &\n";} else if constexpr (std::is_same_v<decltype(arg), X &&>) {std::cout << "arg = X&&\n";} else if constexpr (std::is_same_v<decltype(arg), const X &&>) {std::cout << "arg = const X &&\n";} else {std::cout << "unknown type\n";}}int main() {std::cout << std::boolalpha;// T&& bind to lvalue and const lvalueX x1{};const X x2{};func4(x1); // arg = X&func4(x2); // arg = const X &// T&& bind to rvalue and const rvaluefunc4(X{}); // arg = X&&func4(std::move(x1)); // arg = X&&func4(std::move(x2)); // arg = const X &&// auto&& bind to lvalue referenceX x3{};auto &&x31 = x3;std::cout << std::is_same_v<decltype(x31), X &> << std::endl; // true// auto&& bind to rvalue referenceauto &&x4 = X{};std::cout << std::is_same_v<decltype(x4), X &&> << std::endl; // true// auto&& in lambdaauto sum = [](auto &&... args) { return (args + ...); };std::cout << funcInvocation(sum, 1, 2, 3, 4, 5, 6) << std::endl; // 21return 0;}
🐂 引用类型识别
左值引用:
语法形式为 T&,比较好识别
通用引用 (转发引用):
语法形式为 T&&,主要就两个应用场景,并且必须有类型推导过程
- 形如 T&& 的函数模板参数
- 形如 auto&& 的 auto 变量声明,包括 lambda 形参
右值引用:
语法形式为 T&&,除通用引用之外的都是右值引用
左值引用,只能绑定到左值,但是 const T& 常量左值引用却既可以绑定到左值,也可以绑定到右值,但结果都是常量左值引用。
右值引用只能绑定到右值。
通用引用根据其初始化物的类型,可以绑定到一个左值,也可以绑定到一个右值,比较灵活,一般用来最大化函数参数的普适性。
🐯 总结
- 目前通用引用就只有两种形式,很好识别,识别好了之后再识别右值引用
- 通用引用与 const T& 常量左值引用,都是既可以绑定到左值,也可以绑定到右值,但它们的结果不一样
