Search code examples
c++qt4

Qt: QMutex member in derived QList<XYZ>, no access to QMutex member compile error


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:

  1. When I use 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?
  2. In other languages I'd declare the member as transient. Actually I do not want to have it copied. Is there a declaration for just ignoring it?
  3. Or is writing an assignment / copy operator the better approach?

Solution

  • 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.