gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-27 23:48:55 26 4
gpt4 key购买 nike

我目前正在通读《C++ 并发实践》一书。我似乎无法编译以下代码。一直报错

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

最佳答案

Is the copy constructor for std::thread being called?

这完全取决于使用 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 实例。就像答案的第一个例子一样。

关于c++ - std::thread 可以用在构造函数初始化列表中吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48271028/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com