【问题标题】:Why can't I create a vector of threads on the fly like this为什么我不能像这样动态创建线程向量
【发布时间】:2015-01-25 21:24:05
【问题描述】:

为什么动态创建线程向量是错误的?我收到编译错误

C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\include\xmemory0(593): error C2280: 'std::thread::thread(const std::thread &)' : 试图引用一个被删除的函数

还有很多其他的东西。

#include <iostream>
#include <thread>
#include <vector>

using std::vector;
using std::thread;
using std::cout;

class obj_on_thread {
public:
    void operator()()
    {
        std::cout << "obj on thread\n";
    }
};

void function_on_thread() {
    std::cout << "function on thread\n";
}

auto named_lambda = []() { std::cout << "named_lambda_on_thread\n"; };

int main(){
    obj_on_thread obj;

    vector<thread> pool {
        thread{ obj },
        thread{ function_on_thread },
        thread{ named_lambda },
        thread{ []() { cout << "anonymous lambda on thread\n"; } }
    };
    cout << "main thread\n";

    for(auto& t : pool)
    {
        if (t.joinable())
        {
            cout << "Joinable = true";
            t.join(); //if called must be called once.
        }
        else
        {
            cout << "this shouldn't get printed, joinable = false\n";
        }
    }
    for (auto& t : pool)
    {
        if (t.joinable())
        {
            cout << " This won't be printed Joinable = true";
        }
        else
        {
            cout << "joinable = false thread are already joint\n";
        }
    }

    return 0;
}

【问题讨论】:

  • @DavidSchwartz 它们是在那里创建的,它们已经右值了。

标签: multithreading c++11


【解决方案1】:

std::vector 的使用initializer_list 的构造函数要求元素是可复制构造的,因为initializer_list 本身需要这样做(其底层“存储”实现为复制构造的临时数组)。 std::thread 不可复制构造(此构造函数已删除)。

http://en.cppreference.com/w/cpp/utility/initializer_list

底层数组是一个临时数组,其中每个元素都是 复制初始化...

没有解决这个问题的好方法 - 你不能一次初始化所有线程,但你可以使用(多个调用,每个线程一个 - 不幸的是):

  • emplace_back():

    pool.emplace_back(obj);
    
  • push_back() 带右值:

    pool.push_back(thread{obj});
    
  • push_back() 带有明确的move()s:

    auto t = thread{obj};
    pool.push_back(std::move(t));
    

【讨论】:

  • .... 这太愚蠢了。如果您提出解决方法(即可能是emplace_back),您可以投票。
  • @LightnessRacesinOrbit 抓紧你的马......我正在为帖子添加评论......我可以随意投票
  • 我看到解决方法是使用 push_back(std::thread(...)) 或 emplace_back 等。
  • @cpp_hex - push_back 仅在您使用右值(或 move 对象)时才有效,但 emplace_back 可以。
  • @LightnessRacesinOrbit - 完成,无需争论 (; 最初我认为 OP 没有询问如何修复它,只是为什么会出现错误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-01-16
  • 2012-04-22
  • 2015-09-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多