std :: move参数通过值传递

时间:2019-08-29 10:06:57

标签: c++ parameter-passing move-semantics

我需要有关这段代码的帮助:

void foo(std::promise<std::string> p) {
    try {
        std::string result = "ok";
        p.set_value(std::move(result));
    } catch (...) {
        std::current_exception();
    }

}

int main() {
    std::promise<std::string> promise;
    std::future<std::string> f = promise.get_future();
    std::thread t(foo, std::move(promise));
    t.detach();

    std::string res = f.get();

    return 0;
}

std :: move()用法是什么意思? p是否按值传递(因此是副本)?

1 个答案:

答案 0 :(得分:4)

pfoo中的局部变量。在调用foo之前,必须先创建p。创建它有两种可能性:通过复制构造函数或通过移动构造函数。 std::promise是可移动类,无法复制。因此,创建它的唯一方法是调用promise(promise&&)-移动构造函数。通过

std::move(promise)

您正在将p转换为promise&&,然后编译器可以选择promise(promise&&)promise从main移到p内部的foo中。

因此,这里没有制作promise的副本。