我正在并发编程课上学习 futures。我的教授在她的幻灯片中说明了这一点:
"Valid" futures are future objects associated to a
shared state, and are constructed by calling one of the following functions:
async
promise::get_future
packaged_task::get_future
future objects are only useful when they are valid. Default-constructed future objects are not valid (unless move-assigned a valid future).
我无法理解上面的意思,尤其是“除非移动分配了一个有效的 future ”部分。有人可以用简单的术语解释一下吗,也许还可以显示一些示例代码?
最佳答案
如 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
的状态移动 到this
。这意味着如果 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
调用移动构造函数将导致valid() == true
仅 如果other.valid()
在从它移动之前是true
。否则为假。
关于c++ - 有效 future 与默认构建 future ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40344055/