"Valid" futures arefutureobjects associated to a shared state,and are constructed by calling one of the following functions: async promise::get_future packaged_task::get_future
futureobjects are only useful when they
arevalid.Default-constructedfutureobjects are
notvalid(unlessmove-assignedavalidfuture).
我无法理解上述的含义,尤其是“除非移动指定有效的未来”部分.有人可以用简单的术语解释一下,也许还会展示一些示例代码吗?
解决方法
std::future
constructor所述:
Default-constructed future objects are not valid
std::future<int> f;
Default constructor. Constructs a std::future with no shared state.
After construction,valid() == false
.
至于其他部分:
(unless move-assigned a valid future)
这里的含义是将调用移动构造函数(future(future&& other)#2),其中指出:
Move constructor. Constructs a std::future with the shared state of
other using move semantics. After construction,other.valid() == false
.
基本上,此构造函数中的其他状态将移至此状态.这意味着如果other.valid()== true,那么在移动构造函数返回后,other.valid()将为false,this.valid()将为true.如果other.valid()以false开头,则两者都将以false结尾.
std::future<int> fut; // fut.valid() == false,default constructor std::future<int> valid_fut = std::async(std::launch::async,[](){ return 42; }); // obtain a valid std::future.. // valid_fut.valid() == true here //now move valid_fut into new_fut std::future<int> new_fut(std::move(valid_fut)); // new_fut.valid() == true // valid_fut.valid() == false
总结一下:
>调用std :: future的默认构造函数将导致valid()== false.总是.>调用std :: future的move构造函数只有在other.valid()为true之前才会生成valid()== true.否则就错了.