Reputation: 907
I need some help regarding this piece of code:
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;
}
What's the meaning of the std::move() usage? Is p
passed by value (so a copy)?
Upvotes: 1
Views: 177
Reputation: 20928
p
is local variable inside foo
. Before foo
is invoked, p
must be created. There are two possibilities to create it: by copy constructor or by move constructor. std::promise
is movable class, it cannot be copied. So only way to create it is call promise(promise&&)
- move constructor. By
std::move(promise)
you are casting p
to promise&&
, then the compiler can select promise(promise&&)
to move promise
from main into p
inside foo
.
So no copy of promise
is made here.
Upvotes: 4