I have a derived QList<MyClass>
, with a member QMutex
.
class WaypointList : public QList<Waypoint> {
private:
mutable QMutex _mutex; /*!< Mutex for thread safety */
..
} // HERE COMPILE ERROR, in this line
Compiling, I get C2248: 'QMutex::operator =' : cannot access private member declared in class 'QMutex'
The reason is that QMutex
is not copyable (Q_DISABLE_COPY
, related SO Question). Here it is recommended to make the member a pointer. Is that the best way to do it?
Remarks:
QMutex _mutex
in a derived Q_OBJECT
class, it works fine. Any idea why I get the error here and not with a Q_OBJECT
class?The reason it doesn't have an issue with QObject is that QObject is also non-copyable, so it's not an issue.
In your case, the correct answer is to define your own copy and assignment operators, so that they copy/assign the list, but the object has it's own mutex. That way, it will behave as you expect. There is no keyword in C++ to tell the compiler you want this behavior, you have to do it yourself. In this case, since it's a mutex, you'll probably want to use the mutex properly to ensure the copy is atomic.
Another option is to disable copying/assignment on your new class, but from your question I don't believe that is what you want to do. Finally, if you do decide to use a pointer to the QMutex, you will probably want to create your own copy/assignment operators to handle the raw pointer properly, to prevent a leak.