const转发参考给出错误C2440:'正在初始化':无法从'const std :: string'转换为'const std :: string &&'

问题描述 投票:1回答:1

以下给出了编译器错误:

  #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

c++ c++17
1个回答
0
投票

[get_name()重新运行左值引用,则为lvalue;]]

函数调用或重载的运算符表达式,其返回类型为左值引用

[const auto&&是右值引用,不能绑定到左值。

[const auto& name2 = get_name();有效,因为name2是左值引用,可以绑定到左值。

auto&& name1 = get_name();起作用是因为name1forwarding reference;取决于初始化程序,get_name()是一个值,然后name1是一个左值引用,可以正常工作。

© www.soinside.com 2019 - 2024. All rights reserved.