如何将右值引用从调用者传递给被调用者
How to pass rvalue reference from caller to callee
假设我有下面的代码
#include <iostream>
void foo(std::string && s) { std::cout << s; }
void bar(std::string && s) { foo(s); }
int main() {
bar("abc");
return 0;
}
我遇到编译错误:
error: cannot bind ‘std::string {aka std::basic_string}’ lvalue
to ‘std::string&& {aka std::basic_string&&}’ void
bar(std::string && s) { foo(s); }
使用 <utility>
中的 std::move
:
#include <iostream>
#include <utility>
void foo(std::string && s) { std::cout << s; }
void bar(std::string && s) { foo(std::move(s)); }
int main() {
bar("abc");
return 0;
}
std::move
是 actually just a little bit of syntactical sugar,但这是转发右值引用的常用方法。
假设我有下面的代码
#include <iostream>
void foo(std::string && s) { std::cout << s; }
void bar(std::string && s) { foo(s); }
int main() {
bar("abc");
return 0;
}
我遇到编译错误:
error: cannot bind ‘std::string {aka std::basic_string}’ lvalue to ‘std::string&& {aka std::basic_string&&}’ void bar(std::string && s) { foo(s); }
使用 <utility>
中的 std::move
:
#include <iostream>
#include <utility>
void foo(std::string && s) { std::cout << s; }
void bar(std::string && s) { foo(std::move(s)); }
int main() {
bar("abc");
return 0;
}
std::move
是 actually just a little bit of syntactical sugar,但这是转发右值引用的常用方法。