调用一个接受T& 的函数,传入一个类型为T 的右值。
我的两个函数:
std::vector<std::string> get_line();
void check_commands(std::vector<std::string> &line);
我试着这样使用:check_commands(get_line());,但我得到的错误是:
cannot bind non-const lvalue reference of type 'std::vector<std::__cxx11::basic_string<char> >&' to an rvalue of type 'std::vector<std::__cxx11::basic_string<char> >'
为什么?
解决方案
在 check_comm(get_line()); get_line() 的情况下,会返回一个临时的 std::vector<std::string>。
规则指出,你只能将 const 的引用绑定到临时对象上。
check_commands() 另一方面则想要把一个非 const 的引用绑定到参数上——因此编译失败。
要么让 check_commands() 绑定到一个 const 引用上:
void check_commands(std::vector<std::string> const& line){
// ^^^^^^
如果 check_commands() 确实需要对 line 进行修改,请将 get_line() 的返回值保存到一个变量中,以便传入一个左值(lvalue):
auto lin = get_line();
check_comm(lin); // now fine
或者按值传递参数:
void check_commands(std::vector<std::string> line){
// ^ no & here
请注意,后者在传入左值时会拷贝整个 vector,因此很可能不是你真正想要的解决方案,但它确实是一个选项。
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。