为什么我不能像这样动态创建线程向量



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

C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\include\xmemory0(593): 错误 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 threadn";
    }
};
void function_on_thread() {
    std::cout << "function on threadn";
}
auto named_lambda = []() { std::cout << "named_lambda_on_threadn"; };
int main(){
    obj_on_thread obj;
    vector<thread> pool {
        thread{ obj },
        thread{ function_on_thread },
        thread{ named_lambda },
        thread{ []() { cout << "anonymous lambda on threadn"; } }
    };
    cout << "main threadn";
    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 = falsen";
        }
    }
    for (auto& t : pool)
    {
        if (t.joinable())
        {
            cout << " This won't be printed Joinable = true";
        }
        else
        {
            cout << "joinable = false thread are already jointn";
        }
    }
    return 0;
}

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

最新更新