微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

原文地址:https://www.jb51.cc/c/119931.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐