我需要有关这段代码的帮助:
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
是否按值传递(因此是副本)?
答案 0 :(得分:4)
p
是foo
中的局部变量。在调用foo
之前,必须先创建p
。创建它有两种可能性:通过复制构造函数或通过移动构造函数。 std::promise
是可移动类,无法复制。因此,创建它的唯一方法是调用promise(promise&&)
-移动构造函数。通过
std::move(promise)
您正在将p
转换为promise&&
,然后编译器可以选择promise(promise&&)
将promise
从main移到p
内部的foo
中。
因此,这里没有制作promise
的副本。