C++ for循环中的向量push_back异步对象
我正在用 C++11 编写一个 for 循环,其中需要将异步对象推回到向量上。我想将对象初始化分为两个步骤:
std::vector<std::future<bool>> asyncThreads;
for (int i = 0; i < processorCount; i++) {
auto boundFunc = std::bind(&Foo::foo, this);
auto asyncThread = std::async(std::launch::async, boundFunc)
asyncThreads.push_back(asyncThread);
}
现在我确实意识到 boundFunc
和 asyncThread
对象在 for 循环结束时超出了范围(>push_back
函数应该复制/移动值),但是为什么直接在 push_back 调用
中声明对象可以工作呢?就像这样:
std::vector<std::future<bool>> asyncThreads;
for (int i = 0; i < processorCount; i++) {
asyncThreads.push_back(std::async(std::launch::async, std::bind(&Foo::foo, this)));
}
I was coding a for loop in C++11, where I needed to push back an async object onto a vector. I wanted to split the object initialization into two steps:
std::vector<std::future<bool>> asyncThreads;
for (int i = 0; i < processorCount; i++) {
auto boundFunc = std::bind(&Foo::foo, this);
auto asyncThread = std::async(std::launch::async, boundFunc)
asyncThreads.push_back(asyncThread);
}
Now I do realize that both boundFunc
and asyncThread
objects go out of scope at the end of the for loop (the push_back
function should copy/move the values though), but then why does directly declaring the objects in the push_back call
work? Like so:
std::vector<std::future<bool>> asyncThreads;
for (int i = 0; i < processorCount; i++) {
asyncThreads.push_back(std::async(std::launch::async, std::bind(&Foo::foo, this)));
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
std::future
对象不可复制,但可移动。因此,您必须对对象调用 move 将其推送到向量上。A
std::future
object is not copyable, but moveable. So therefore, you must call move on the object to push it onto the vector.