我目前正在阅读“行动中的C++并发”一书。我似乎无法编译以下代码。我一直在犯错误
error: field of type 'std::thread' has private copy constructor正在调用std::线程的复制构造函数吗?
class scoped_thread
{
std::thread t;
public:
explicit scoped_thread(std::thread t_):
t(std::move(t_))
{
if(!t.joinable())
throw std::logic_error("No thread");
}
~scoped_thread()
{
t.join();
}
scoped_thread(scoped_thread const&)=delete;
scoped_thread& operator=(scoped_thread const&)=delete;
};
int main() {
int some_local_state = 0;
scoped_thread t(std::thread(func(some_local_state)));
}发布于 2018-01-15 21:48:18
正在调用std::线程的复制构造函数吗?
这完全取决于使用scoped_thread的代码。
请注意,std::thread是可移动的,但不可复制类型。
这意味着,下一段代码工作正常:
scoped_thread st(std::thread{});因为t_是通过移动构造函数创建的。
但是,如果您创建了一个std::thread实例,然后尝试将其包装到scoped_thread中,如下所示:
std::thread t;
scoped_thread st(t);然后,调用复制构造函数的尝试发生,您将得到一个编译错误。
由于scoped_thread似乎实现了RAII,正确的使用方法是包装一个未命名的std::thread实例,如答案的第一个示例所示。
发布于 2018-01-15 22:03:47
列出的代码是正确的。但是,对于编译器,-std没有设置为c++11。这可能使编译器使用复制构造函数,因为移动语义在较早的C++版本中不可用。
https://stackoverflow.com/questions/48271028
复制相似问题