'future'已明确标记为已删除

时间:2016-01-19 10:35:33

标签: c++ macos asynchronous future

我正在尝试构建一个Async应用程序以允许并行处理大型列表,在通过Google搜索学习C ++两天后,我想出了标题错误,来自以下代码:

//
//  main.cpp
//  ThreadedLearning
//
//  Created by Andy Kirk on 19/01/2016.
//  Copyright © 2016 Andy Kirk. All rights reserved.
//

#include <iostream>
#include <thread>
#include <vector>
#include <chrono>
#include <future>

typedef struct {
    long    mailing_id;
    char    emailAddress[100];
} emailStruct ;

typedef struct {
    long    mailing_id = 0;
    int     result = 0;
} returnValues;

returnValues work(emailStruct eMail) {

    returnValues result;

    std::this_thread::sleep_for(std::chrono::seconds(2));

    result.mailing_id = eMail.mailing_id;

    return result;
}

int main(int argc, const char * argv[]) {

    std::vector<emailStruct>    Emails;
    emailStruct eMail;

    // Create a Dummy Structure Vector
    for (int i = 0 ; i < 100 ; ++i) {
        std::snprintf(eMail.emailAddress,sizeof(eMail.emailAddress),"user-%d@email_domain.tld",i);
        eMail.mailing_id = i;
        Emails.push_back(eMail);
    }


    std::vector<std::future<returnValues>> workers;

    int worker_count = 0;
    int max_workers  = 11;


    for ( ; worker_count < Emails.size(); worker_count += max_workers ){

        workers.clear();

        for (int inner_count = 0 ; inner_count < max_workers ; ++inner_count) {
            int entry = worker_count + inner_count;
            if(entry < Emails.size()) {
                emailStruct workItem = Emails[entry];
                auto fut = std::async(&work, workItem);
                workers.push_back(fut);
            }
        }

        std::for_each(workers.begin(), workers.end(), [](std::future<returnValues> & res) {
            res.get();
        });

    }

    return 0;
}

真的不确定我做错了什么,找到了有限的答案。如果相关,它在OSX 10上,和XCode 7。

2 个答案:

答案 0 :(得分:4)

future类有copy constructor deleted,因为确实不想拥有它的多个副本。

要将其添加到矢量,您必须移动它而不是复制它:

workers.push_back(std::move(fut));

答案 1 :(得分:0)

如果将将来的对象(在线程内)传递给需要按值传递的函数,也会引发此错误。

例如,当您过未来时,这会引发错误:

void multiplyForever(int x, int y, std::future<void> exit_future);

multiplyForever(3, 5, fut);

您可以通过参考未来来解决它:

void multiplyForever(int x, int y, std::future<void>& exit_future);

multiplyForever(3, 5, fut);