为什么调用 const 引用而不是右值引用以及 std::move 是如何工作的?

问题描述 投票:0回答:1
#include <iostream>

void bar(std::string& s) { std::cout << "ref" << std::endl;}
void bar(const std::string& s) { std::cout << "const ref" << std::endl;}
void bar(std::string&& s) { std::cout << "rvalue ref" << std::endl;}

int main (int argc, char *argv[]) {
  const std::string text{"text"};
  bar(text); 
  bar(std::string{"text"});
  bar("text"); 

  std::string text1{"text"};
  bar(text1);

 bar(std::move(text)); 

  return 0;
}

我希望为最后一个函数调用打印右值引用,而不是常量引用。为什么打印 const ref 而不是 rvalue ref?我认为 std::move 接受文本变量并向其添加 && 并将其转换为右值引用,但显然它不能那样工作。既然 rvalue 可以绑定到 rvalue ref 和 const ref,那么哪一个优先呢?有人可以帮助我吗?

c++ rvalue-reference lvalue-to-rvalue pass-by-const-reference pass-by-rvalue-reference
1个回答
1
投票

将 const 值转换为 rvalue 不会神奇地丢弃 const 限定符。所以本质上是

const std::string&&
。您提供的函数中与该类型最接近的匹配是
const std::string&

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