代码之家  ›  专栏  ›  技术社区  ›  user2793618

C++向量推回for循环中的异步对象

  •  0
  • user2793618  · 技术社区  · 3 年前

    我在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 call 工作就像这样:

        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)));
        }
    
    0 回复  |  直到 3 年前
        1
  •  1
  •   François Andrieux    3 年前

    A. std::future 对象不可复制,但可移动。因此,必须调用对象上的move来将其推到向量上。