Home > Blockchain >  C vector push_back async object in for loop
C vector push_back async object in for loop

Time:03-25

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)));
    }

CodePudding user response:

A std::future object is not copyable, but moveable. So therefore, you must call move on the object to push it onto the vector.

  • Related