0

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?
Community
  • 1
  • 1
Horst Walter
  • 13,663
  • 32
  • 126
  • 228

2 Answers2

2

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.

Dave S
  • 20,507
  • 3
  • 48
  • 68
  • You got it right, I'd prefer to keep "copy", and need the mutex during copy and assignment from different threads. I give it a trial with own operator (and then I'll be back :-) – Horst Walter Sep 17 '12 at 14:08
1

Q_OBJECT is a macro that must appear in the private section of a class definition that declares its own signals and slots or that uses other services provided by Qt's meta-object system (here). This macro requires the class to be a subclass of QObject. QObject has neither a copy constructor nor an assignment operator (take a look here).

Sorry if I repeat something that you know. I would suggest to disable explicitly copy constructor and assignment operator of your class with a Q_DISABLE_COPY macro:

class WaypointList : public QList<Waypoint> {
private:
    Q_DISABLE_COPY(WaypointList)
    mutable QMutex _mutex; /*!< Mutex for thread safety */
    ..
};

Hope, this will help.

ololuki
  • 377
  • 1
  • 7
  • 14
besworland
  • 747
  • 2
  • 7
  • 17
  • This also works, but I stick with a version of the class I can copy (=> assignment operator implemented). Thanks for your hint. – Horst Walter Sep 17 '12 at 14:41