简体   繁体   中英

std::future<>::get empties the result

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 .

From cppreference on std::future<T>::get :

Any shared state is released. valid() is false after a call to this method.

And just before mentions that

The behavior is undefined if valid() is false 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM