参考资料:
lvalue, glvalue, xvalue, rvalue, prvalue 的关系
下图来自 CppCon:Back to Basics: Forwarding References - How to Forward Parameters in Modern C++ - Mateusz Pusz - CppCon 2023
lvalue(左值): 有标识符的值,但没被应用 std::move()
glvalue(泛左值): 有标识符的值
xvalue(亡值): 有标识符的值,且被应用了 std::move()
rvalue(右值): 要么是 xvalue,要么是 prvalue
prvalue(纯右值): 没有标识符的值
std::move()
std::move() 本身并不会引发移动,它只是一个将参数类型转换为右值引用类型的转换器。
万能引用、const左值引用和完美转发
Both forwarding references and const lvalue references bind to everything. However, the former might be more expensive in compile time.
因此,万能引用的 use case 几乎仅限于将实参完美转发给另一个函数,而使用了万能引用的函数本身除了转发之外,不做任何事情。
引用折叠——std::forward()的技术原理
总结:如果你想保证,在传递参数的前后,参数的值类型不变,那么就用完美转发,否则就用 const reference。
注意:在构造函数中使用完美转发时,需要当心完美转发破坏你的构造函数。