简体   繁体   English

C++ 向量 push_back 异步 object 在 for 循环中

[英]C++ vector push_back async object in for loop

I was coding a for loop in C++11, where I needed to push back an async object onto a vector.我在 C++11 中编写了一个 for 循环,我需要将异步 object 推回一个向量。 I wanted to split the object initialization into two steps:我想将 object 初始化分成两步:

    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?现在我确实意识到在 for 循环结束时boundFuncasyncThread对象 scope 中的 go( push_back function 应该复制/移动值),但是为什么直接在push_back call中声明对象有效? 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)));
    }

A std::future object is not copyable, but moveable. std::future object 不可复制,但可移动。 So therefore, you must call move on the object to push it onto the vector.因此,您必须在 object 上调用 move 以将其推送到矢量上。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM