c++ - 何时在函数调用中使用 move

标签 c++ move

我目前正在学习有关所有 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/

相关文章:

c++ - 一个for循环的测试条件可以放多个关系表达式吗?

c++ - 如何让正则表达式匹配句子的中间?

c++ - BST前序遍历并将树内容写入临时数组

c++ - move 语义会阻止在这里复制吗?

html - Div 仅在缩小时 move

c++ - 在 Eclipse C++ 索引中包含所有文件

c++ - vector 追加

c++ - std::bind 如何按值获取可变参数,即使它具有通用引用?

安卓猴赛跑者 : Touch with MOVE

ruby - Rails/重命名或 move 文件