以下给出了编译器错误:
#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&
它会编译 - 但不会绑定(bind)到值。
auto&&
将绑定(bind)到任何东西,这样自然也可以工作。
但是,在这种情况下 const auto&& 不绑定(bind)背后的逻辑是什么?
我知道 auto&&
会保留常量性 - 但有没有一种方法可以使 const
显式,同时引用/值不可知?
动机:
对于函数内部的“正常编程工作”等,如果能够这样说就太好了:“我不关心它是一个值还是引用 - 但我不会在其余部分更改它函数”。
考虑到当前的语言,这应该是可能的。
相关问题: Why adding `const` makes the universal reference as rvalue
最佳答案
For 'normal programming work' inside functions etc. it would be great to be able to say something like: "I do not care if it's a value or reference - but I do not change it for the rest of the function".
您手头已经有了激励您的解决方案:使用 const auto&
。 const auto&
将绑定(bind)到:
- const 左值引用
- 左值引用
- const 右值引用
- 右值引用
- 此外,它将延长返回值的生命周期
所以你已经得到了你需要的一切。是的,它与 const 右值引用不同,但如果您只是使用它,那并不重要,因为无论如何您都无法从它移动,因为它是 const。
最后一点:auto&&
将始终是一个引用。它是带有推导的转发引用,但您的最终变量将始终是引用(右值引用或左值引用,但绝不是“值”)。也许那是/是一个误解?
关于c++ - const 转发引用给出错误 C2440 : 'initializing' : cannot convert from 'const std::string' to 'const std::string &&' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58299331/