我目前正在学习有关所有 c++11/14 功能的更多信息,并想知道何时在函数调用中使用 std::move。
我知道在返回局部变量时我不应该使用它,因为这会破坏返回值优化,但我真的不明白在函数调用中强制转换为右值实际上有什么帮助。
最佳答案
当一个函数接受一个右值引用时,你必须提供一个右值(或者通过已经有一个右值,或者使用std::move
创建一个xvalue)。例如
void foo(std::string&& s);
std::string s;
foo(s); // Compile-time error
foo(std::move(s)); // OK
foo(std::string{}) // OK
当函数接受 值 时,您可以使用 std::move
move 构造函数参数而不是复制构造。例如
void bar(std::string s);
std::string s;
bar(s); // Copies into `s`
bar(std::move(s)); // Moves into `s`
当一个函数接受一个转发引用时,您可以使用std::move
来允许该函数将对象进一步向下 move 到调用堆栈。例如
template <typename T>
void pipe(T&& x)
{
sink(std::forward<T>(x));
}
std::string s;
pipe(s); // `std::forward` will do nothing
pipe(std::move(s)); // `std::forward` will move
pipe(std::string{}); // `std::forward` will move
关于c++ - 何时在函数调用中使用 move ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55865219/