【发布时间】: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