了解引用绑定

Understanding reference binding

本文关键字:绑定 引用 了解      更新时间:2023-10-16

我们不能将非常量左值引用绑定到右值,但它可以绑定到常量。我们不能将右值引用也绑定到左值。其实标准是这么说的:

8.5.3/5.2:

引用应为对非易失常量的左值引用类型(即,cv1应为const(,或者引用应为右值引用。

但是,对于这些事情,还有比"标准报这么说"更好的解释吗?

因为它没有语义意义。

不能将非常量左值引用绑定到右值,因为修改右值意味着什么?根据定义,没有其他人会看到结果,所以这没有意义。

int& i = 3;
//should change referenced location, but we aren't referencing a memory location
i = 5; 

不能将右值引用绑定到左值,因为存在右值引用是为了便于对其引用进行破坏性优化。你不希望你的物体被任意地从你身下移出,所以标准不允许这样做

void process_string (std::string&&);
std::string foo = "foo";
//foo could be made garbage without us knowing about it
process_string (foo); 
//this is fine
process_string (std::move(foo));

想想一些真实的案例:

#include <vector>
void f1( int& i ){i = 1;}
void f2( const int& i ){i = 1;}
void f3( std::vector<int>&& v ){auto v_move{v};}
int main()
{
    f1(3); // error: how can you set the value of "3" to "1"?
    f2(3); // ok, the compiler extend the life of the rvalue "into" f2
    std::vector<int> v{10};
    f3(v); // error: an innocent looking call to f3 would let your v very different from what you would imagine
    f3(std::vector<int>{10}); // ok, nobody cares if the rvalue passed as an argument get modified
}