Stroustrup的guarded_thread类移动赋值运算符错误问题咨询
guarded_thread Inheriting from std::thread Let's break down why you're hitting a move assignment error with the guarded_thread class from The C++ Programming Language (4th Ed., p1215), and walk through how to fix it.
The Root Cause
When you define a custom destructor for a class (like we did for guarded_thread to handle automatic joining), the C++ compiler stops generating default move operations—including the move assignment operator. Even though std::thread has a valid move assignment operator, our derived class doesn't inherit it automatically unless we explicitly tell the compiler to do so.
Solution 1: Inherit the Base Class's Move Assignment Operator
The cleanest fix is to bring std::thread's move assignment operator into the guarded_thread scope, just like we did with the constructors. Here's the updated code:
struct guarded_thread : std::thread { // Inherit all constructors from std::thread using std::thread::thread; // Explicitly inherit std::thread's move assignment operator using std::thread::operator=; ~guarded_thread() { if (joinable()) join(); } };
This works because the using declaration pulls the base class's move assignment operator into our derived class, allowing guarded_thread to support move assignments exactly like std::thread does, while retaining our RAII cleanup in the destructor.
Solution 2: Implement a Custom Move Assignment Operator
If you prefer more control over the move behavior, you can write a custom move assignment operator that aligns with the RAII guarantee of guarded_thread:
struct guarded_thread : std::thread { using std::thread::thread; guarded_thread& operator=(guarded_thread&& other) noexcept { // First, join our own thread if it's still running if (joinable()) { join(); } // Move the base class state from the other thread std::thread::operator=(std::move(other)); return *this; } ~guarded_thread() { if (joinable()) join(); } };
This version ensures we properly clean up any existing thread before taking ownership of the moved-from thread, which matches the safety pattern the original guarded_thread was designed for.
Either approach will resolve the move assignment error while preserving the RAII behavior Stroustrup intended.
内容的提问来源于stack exchange,提问作者SSteven

