其他分享
首页 > 其他分享> > std::move std::forward及使用

std::move std::forward及使用

作者:互联网

概念

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)...);
}

折叠规则为:

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

标签:std,LOG,lvalue,move,&&,forward,Consumes
来源: https://www.cnblogs.com/vaughnhuang/p/16573948.html