可以在构造函数初始化列表中使用std :: thread吗?

时间:2018-01-15 21:40:02

标签: c++ multithreading c++11

我目前正在阅读C ++ Concurrency in Action一书。我似乎无法获得以下代码进行编译。我一直在犯错误

error: field of type 'std::thread' has private copy constructor

是否调用了std :: thread的拷贝构造函数?

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

2 个答案:

答案 0 :(得分:3)

  
    

是否调用了std :: thread的拷贝构造函数?

  

完全取决于使用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实例。

答案 1 :(得分:0)

列出的代码是正确的。但是,编译器-std未设置为c++11。这个可能使用复制构造函数离开了编译器,因为旧的C ++版本中没有移动语义。

相关问题