(C++) std::move std::forward及使用

2022-12-27,

概念

std::ref :针对std::thread,需要把实参显式转换为引用类型;
std::move :无条件把参数转换为右值;但是右值赋值给新变量时,实际还要看是否满足右值条件,如const std::string&& 赋值后,实际调用的是左值构造/赋值;
std::forward :根据实参类型决定传递给下一层function的参数类型使用;被称为完美转发 (也叫精确传递);

std::forward比较多的是配合 T&& 使用(使用在template代码中);其作用之一是将参数本层调用传递给下一层调用。

void log_and_consume(std::string&& message) {
std::cout << "LOG: logging with rvalue\n";
consume(message);
} void log_and_consume(std::string const& message) {
std::cout << "LOG: logging with lvalue\n";
consume(message);
} int main() {
auto msg = std::string("sample message");
log_and_consume(msg);
log_and_consume("sample message");
}

期望的输出:

LOG: logging with lvalue
Consumes an lvalue
LOG: logging with rvalue
Consumes an rvalue

实际的输出:

LOG: logging with lvalue
Consumes an lvalue
LOG: logging with rvalue
Consumes an lvalue

折叠规则

template <class... Args>
void forward(Args&&... args) {
f(std::forward<Args>(args)...);
}

折叠规则为:

&& && -> &&
& && -> &
& & -> &
&& & -> &

move/forward只是执行类型转换,且在编译期间。

(C++) std::move std::forward及使用的相关教程结束。

《(C++) std::move std::forward及使用.doc》

下载本文的Word格式文档,以方便收藏与打印。