【问题标题】:const forwarding reference gives error C2440: 'initializing': cannot convert from 'const std::string' to 'const std::string &&'const 转发参考给出错误 C2440:'initializing': cannot convert from 'const std::string' to 'const std::string &&'
【发布时间】:2023-11-12 15:44:02
【问题描述】:

以下给出编译器错误:

  #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;
  }

神螺栓链接:https://godbolt.org/z/l6IQQ7

如果我使用const auto&amp;,它会编译——但这不会绑定到值。 auto&amp;&amp; 将绑定到任何东西,这样自然也能正常工作。 但是,在这种情况下 const auto&amp;&amp; 不绑定背后的逻辑是什么? 我知道auto&amp;&amp; 会保持不变性 - 但有没有办法让const 显式同时引用/值不可知

动机:

对于函数内部的“正常编程工作”等,如果能够说类似的话会很棒:“我不在乎它是值还是引用 - 但我不会在其余部分更改它函数”.

考虑到当前的语言,这应该是可能的。

相关问题: Why adding `const` makes the universal reference as rvalue

【问题讨论】:

  • 一个duplicate?这个问题是关于模板类型推导的,但由于本例中规则与auto相同,我想我们可以关闭它吗?
  • @lubgr 我确实看到了 - 它的框架不一样 - 我也在寻求“解决方案”
  • 一个“解决方案”是只使用 const auto&。它绑定到一切。如果您以某种方式获得 const rvalue ref,您将不会获得任何优势
  • @phön ty,这有点令人惊讶,请写一个带有解释的答案。
  • @phön 我的意思是,直觉上你会认为像这样的“常量引用”的返回值会在该语句之后被破坏。

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


【解决方案1】:

对于函数内部的“正常编程工作”等,这会很棒 能够说类似的话:“我不在乎它是价值还是 参考 - 但我不会为其余的功能更改它”。

您已经有了激发动力的解决方案:使用const auto&amp;const auto&amp; 将绑定到:

  • const 左值引用
  • 左值引用
  • const rvalue 引用
  • 右值引用
  • 此外,它将延长返回值的生命周期

所以你得到了你需要的一切。是的,它与 const rvalue ref 不同,但如果你只使用它,那并不重要,因为无论如何你都无法从中移动,因为它是 const。

最后一点:auto&amp;&amp; 将始终作为参考。它是一个带有扣除的转发引用,但您的最终变量将始终是一个引用(右值引用或左值引用,但绝不是“值”)。也许那是/是一个误解?

【讨论】: