C++ 防护螺纹C++;
我试图创建一个“受保护的线程”,但收到一个错误“operator=”是“std::\uu 1::thread”的私有成员。这是我的密码:C++ 防护螺纹C++;,c++,multithreading,stdthread,C++,Multithreading,Stdthread,我试图创建一个“受保护的线程”,但收到一个错误“operator=”是“std::\uu 1::thread”的私有成员。这是我的密码: struct guarded_thread : std::thread{ using std::thread::thread; using std::thread::operator=; ~guarded_thread(){if(joinable())join();} }; 一个函数完成了这项工作,但我想知道如何以另一种方式创建它 v
struct guarded_thread : std::thread{
using std::thread::thread;
using std::thread::operator=;
~guarded_thread(){if(joinable())join();}
};
一个函数完成了这项工作,但我想知道如何以另一种方式创建它
void Guarded_thread(std::thread &Thread){
if (Thread.joinable()) {
Thread.join();
}
}
std::thread
s析构函数不是虚拟的。因此,您将无法多态地使用guarded_线程
,与使线程成为成员相比,继承没有什么好处std::thread
无法复制,这基本上就是错误所说的,因此guarded\u thread
也无法复制。但是,它可以移动:
#include <thread>
#include <iostream>
struct guarded_thread {
std::thread t;
~guarded_thread() {
if(t.joinable()) {
t.join();
}
}
};
void foo(guarded_thread&& t) {}
int main() {
foo(guarded_thread{ std::thread{ [](){ std::cout << "hello world"; }}});
}
#包括
#包括
结构保护线程{
标准:螺纹t;
~u线程(){
if(t.joinable()){
t、 join();
}
}
};
void foo(受保护的线程和线程){}
int main(){
foo(protected_thread{std::thread{[](){std::cout请显示一个并解释您的代码应该做什么。错误不是很简单吗?您正在尝试使用std::thread
上私有的赋值运算符。请注意,C++20有std::jthread
,并且(公开的)从std类型继承并不总是最好的主意。std::thread
无法复制,因此不能从中继承任何类。但是您可以为您的类使用一个简单的std::thread
成员变量,而不是继承。代码也没有考虑到线程可以无限期运行,并且在des时运行调用tructor。请求jthread从析构函数停止,这是jthread的一个特性。