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

发布于 2025-01-16 07:47:05 字数 868 浏览 2 评论 0原文

我正在用 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);
    }

现在我确实意识到 boundFuncasyncThread 对象在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

岁月如刀 2025-01-23 07:47:05

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文