Reputation: 11178
I have a threaded function that would return the external IP, and thought I could use it with std::future
:
std::future<std::string> GetIP4;
GetIP4 = std::async([]() -> std::string
{
return GetWanIP();
});
When later in the code I call GetIP4.get()
, I get a std::string
. However this empties the object, so the next time I try to call get
from another thread it crashes.
Is this the intended behaviour of std::future<>::get()
? Is it a scenario "I have it only once"? I didn't find anything in the documentation.
Upvotes: 0
Views: 105
Reputation: 29072
From cppreference on std::future<T>::get
:
Any shared state is released.
valid()
isfalse
after a call to this method.
And just before mentions that
The behavior is undefined if
valid()
isfalse
before the call to this function.
Since valid()
must be true
to call get()
and get()
causes valid()
to become false
, then it isn't possible to get()
the same future
result more than once.
Upvotes: 5