std::move 参数按值传递
std::move argument passed by value
关于这段代码我需要一些帮助:
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
是否按值传递(因此是副本)?
p
是foo
里面的局部变量。在调用 foo
之前,必须创建 p
。创建它有两种可能性:通过复制构造函数或通过移动构造函数。 std::promise
可移动class,不可复制。所以创建它的唯一方法是调用 promise(promise&&)
- 移动构造函数。通过
std::move(promise)
你正在将 p
转换为 promise&&
,那么编译器可以 select promise(promise&&)
将 promise
从 main 移动到 p
里面foo
.
所以这里没有复制promise
。
关于这段代码我需要一些帮助:
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
是否按值传递(因此是副本)?
p
是foo
里面的局部变量。在调用 foo
之前,必须创建 p
。创建它有两种可能性:通过复制构造函数或通过移动构造函数。 std::promise
可移动class,不可复制。所以创建它的唯一方法是调用 promise(promise&&)
- 移动构造函数。通过
std::move(promise)
你正在将 p
转换为 promise&&
,那么编译器可以 select promise(promise&&)
将 promise
从 main 移动到 p
里面foo
.
所以这里没有复制promise
。