【发布时间】:2014-12-14 20:37:08
【问题描述】:
下面的代码按预期编译和工作。
结构(类)A 派生自 std::thread 并扩展为 int 更多。
main 代码创建一些线程,然后等待它们完成。
问题是,虽然代码在 struct A 中没有析构函数的情况下编译,但当析构函数未注释(~A(){})时,我得到:
错误:使用已删除的函数'std::thread::thread(const std::thread&)'
我不知道为什么。
此外,我不明白为什么该代码同时适用于 push_back 和 emplace_back,而根据我的理解,它不应该适用于 push_back。
#include <iostream>
#include <thread>
#include <vector>
struct A : std::thread {
int i;
A(void f(const char*),const char* s,int i_) : std::thread{f,s},i{i_}{
std::cout<<"A created"<<std::endl;
}
//~A(){} // uncomment to see error
};
void dosomething(const char* s){
std::cout<<s<<std::endl;
}
int main(){
std::vector<A> aa;
aa.emplace_back(&dosomething,"hi people",3434);
aa.push_back(A(&dosomething,"hi again people",777));
aa.emplace_back(&dosomething,"hi again people",777);
aa.push_back(A(&dosomething,"hi again people",777));
for(auto& i:aa) i.join();
}
【问题讨论】:
-
哪个编译器版本和选项?我怀疑这可能是编译器错误。
-
至于为什么它与
push_back一起工作,我相信你的结构A有资格自动生成移动构造函数,所以push_back将移动构造A中的来自你传入的临时向量。(注意有一个push_back(value_type &&)重载!) -
-g;-O0;-Wall;-std=c++14;-pthread 既使用 g++ 和 clang++ 也使用 -std=c++11
-
在这里编译:goo.gl/fyGEz8 并在运行时抛出异常。
-
std::thread是可移动的(A在添加析构函数之前也是如此),但不可复制。
标签: c++ multithreading stdthread