Stroustrup演示了一个guarded_thread类,它继承自线程并在其上使用RAII(“The C ++ Programming Language”,4th Ed,pg1215):
struct guarded_thread : std::thread
{
/// inherit the thread class' constructor
/// [CPL], $20.3.5.1
using std::thread::thread;
~guarded_thread()
{
if (joinable())
join();
}
};
我使用代码(也由Stroustrup提供)测试了这个:http://coliru.stacked-crooked.com/a/da67ae51157bcbe4
/// simple use of a guard
void run(int i, int n)
{
guarded_thread t1 {f};
guarded_thread t2;
vector<T> v;
/// ...
if (i < n)
{
thread t3 {g};
/// ...
/// move t3 to outer scope
t2 = move(t3);
}
/// might throw
v[i] = T {};
/// ...
cout << "i=" << i
<< " n=" << n
<< " OK" << endl;
}
但是,测试仪发生以下编译错误:
main.cpp:51:10: error: no viable overloaded '='
t2 = move(t3);
~~ ^ ~~~~~~~~
./guarded_thread.h:12:8: note: candidate function (the implicit copy assignment operator) not viable: no known conversion from 'typename remove_reference<thread &>::type' (aka 'std::__1::thread') to 'const guarded_thread' for 1st argument
struct guarded_thread : std::thread
^
1 error generated.
guarded_thread类也不能继承线程类的赋值运算符,因为后者是私有的。
如何解决此错误?