c – 有效期货与违约构造期货

我正在我的并发编程课中学习期货.我的教授在她的幻灯片中说明了这一点:
"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;

这将调用构造函数#1,其中指出:

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.否则就错了.

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...