C++11关于四个引用的学习
0x01 引用的嵌套
It is permitted to form references to references through type manipulations in templates or typedefs, in which case the reference collapsing rules apply: rvalue reference to rvalue reference collapses to rvalue reference, all other combinations form lvalue reference
引用折叠规则:右值对右值的引用折叠为右值引用,所有其他组合为左值引用。
0x02 左值引用
Lvalue references can be used to alias an existing object (optionally with different cv-qualification):
左值引用可以作为一个已存在对象的别名,且可以用多个别名,别名之间共享一个对象。
1 | int main() |
They can also be used to implement pass-by-reference semantics in function calls:
左值引用可以在函数中引用传递
1 | void double_string(std::string& s) |
When a function’s return type is lvalue reference, the function call expression becomes an lvalue expression:
当一个函数的返回值是左值引用时,这个函数调用表达式也成为了左值表达式
1 | char& char_number(std::string& s, std::size_t n) |
0x03 右值引用
Rvalue referencesRvalue references can be used to extend the lifetimes of temporary objects (note, lvalue references to const can extend the lifetimes of temporary objects too, but they are not modifiable through them):
右值引用可以延长临时对象的生命周期,左值引用加const也能延长生命周期(cppref 的例子,我也不知道有什么用,随便翻译一下吧)
1 | int main() |
More importantly, when a function has both rvalue reference and lvalue reference overloads, the rvalue reference overload binds to rvalues (including both prvalues and xvalues), while the lvalue reference overload binds to lvalues
当一个函数同时有左值和右值的重载时,右值引用重载绑定右值,左值引用重载绑定左值
1 | void f(int& x) |
可以通过std::move将42绑定i2,使得i2成为一个右值
1 | int i2 = 42; |
This makes it possible to move out of an object in scope that is no longer needed:
通过这样就可以舍去作用域中不再需要的对象:(这个例子移去了v)
1 | // |
0x04 Forwarding reference
转发引用是一种特殊的引用,它保留了函数参数的值类别(左值和右值性质不变),从而可以通过 std::forward 进行转发给另一个函数或者类,实现完美转发。(该引用是左右不确定的)
例子1,模板函数参数声明为类模板参数的右值引用
1 | template<class T> |
例子2,auto&&能自动推导。
1 | auto&& vec = foo(); // foo() may be lvalue or rvalue, vec is a forwarding reference |
0x05 Dangling references
生命周期已经结束,但引用仍可以访问(悬挂)访问这样的引用是未定义的行为
If the referred-to object was destroyed (e.g. by explicit destructor call), but the storage was not deallocated, a reference to the out-of-lifetime object may be used in limited ways, and may become valid if the object is recreated in the same storage (see Access outside of lifetime for details).
如果被引用的对象已被销毁(例如通过显式析构函数调用),但存储空间未被清空,则对超出生命周期的对象的引用可以以有限的方式使用,如果在同一存储空间中重新创建该对象,则该引用可能有效(详见超出生命周期的访问)。(deepl翻译的)
1 | std::string& f() |