c++ - const 转发引用给出错误 C2440 : 'initializing' : cannot convert from 'const std::string' to 'const std::string &&'

标签 c++ c++17 forward-reference

以下给出了编译器错误:

  #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/

相关文章:

c++ - 创建一个 C++ 模板函数,它将返回特定大小的 std::array

Scala 前向引用

scala - 前向引用扩展了值(value)问题的定义

redux-form - 通过 Redux Form 传递前向引用?

c++ - 并发写入 unordered_map (C++) 中的不同存储桶?

c++ - 宏使用不需要的大括号替换自身

c++ - C 中两个地址的差异

c++ - 为什么 <iterator> 的 std::size 不能使用原始数组参数

c++ - reinterpret_cast 和结构对齐

指向未确定类的成员函数的指针的 C++ 模板,具有不同的参数,称为参数