以下给出了编译器错误:
#include <string>
const std::string& get_name();
int main(){
auto&& name1 = get_name();//should bind to whatever
const auto& name2 = get_name();//also ok
const auto&& name3 = get_name();//<-not ok, why ?
return 0;
}
链接到Godbolt:https://godbolt.org/z/l6IQQ7
如果使用const auto&
,它将编译-但这不会绑定到值。auto&&
将绑定到任何东西,因此自然也可以工作。但是,在这种情况下不绑定const auto&&
的逻辑是什么?我知道auto&&
将保留常量性-但有一种方法可以使const
明确,同时成为参考/值不可知?
相关问题: Why adding `const` makes the universal reference as rvalue
[get_name()
重新运行左值引用,则为lvalue;]]
函数调用或重载的运算符表达式,其返回类型为左值引用
[
const auto&&
是右值引用,不能绑定到左值。
[const auto& name2 = get_name();
有效,因为name2
是左值引用,可以绑定到左值。
auto&& name1 = get_name();
起作用是因为name1
是forwarding reference;取决于初始化程序,get_name()
是一个值,然后name1
是一个左值引用,可以正常工作。