了解引用绑定
Understanding reference binding
我们不能将非常量左值引用绑定到右值,但它可以绑定到常量。我们不能将右值引用也绑定到左值。其实标准是这么说的:
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
}
相关文章:
- 我想将一个对T类型的非常量左值引用绑定到一个T类型的临时值
- 将常量指针引用绑定到非常量指针
- 运行时错误:引用绑定到类型为"int"的空指针
- 了解C++如何返回引用并绑定到引用
- 模板允许左值与右值引用绑定
- 为什么结构化绑定不使用"auto&"返回对结构成员的引用,而是返回成员本身
- 运行时错误:引用绑定到类型"int"的未对齐地址0xbebebebebebebec6,这需要 4 个字节对齐 (stl_vector.h)
- 无法将类型"T&"的非常量左值引用绑定到类型"T"的右值 t++ std::atomic<T>
- C++通过绑定到引用成员而缩短临时变量寿命?
- C++初始化 std::function 时如何将占位符绑定到引用/引用参数?
- 在其他容器中使用 boost::container::static_vector 时,GCC 编译错误"将'const s'绑定到类型's&'的引用丢弃限定符"
- 为什么定义复制构造函数会给我错误:无法将类型 'obj&' 的非常量左值引用绑定到类型为"obj"的右值?
- 对结构成员的临时绑定引用
- 错误:在类型 "blah blah" 的绑定引用中删除限定符以初始化"some other blah blah"
- 为什么我可以在初始化引用后重新绑定引用?
- 为什么按引用传入会导致绑定引用类型错误
- 返回非常量引用会导致绑定引用错误
- 递归到迭代而不重新绑定引用
- 类型绑定引用中的限定符和 const 类型的初始值设定项中删除
- 为什么C++不允许重新绑定引用?