Important: Please read the Qt Code of Conduct -

QDateTime copy constructor weird behaviour

  • Hi everyone,

    I have a QList<Item> where Item is a class containing a field timestamp of type QDateTime. When I push_back a new item in the list using code like this:

    class Item {
    QDateTime timestamp;

    Item item;

    I expect that the push_back method appends a copy of the item (made using copy constructor of Item) to the list. By default the copy constructor of a class invokes copy constructor of each field declared within that class. In this case copy constructor of Item will invoke copy constructor of QDateTime to create a copy of field timestamp.

    What strangely happens is that, after the insertion, when the Qt Gui terminates its normal thread loop, the program crashes. If I remove the field timestamp from class Item, everything works fine.

    I wonder why, given that QDateTime is not derived from QObject and there is not special attention to pay for its normal construction/destruction.

    FYI: I've been using Qt for not more than 2 months and may be I miss something.

    Thanks a lot for your help


  • Lifetime Qt Champion

    Hi and welcome to devnet,

    Can you provide a minimum sample of code that shows this behavior ?

  • Hi SGalst,

    pasting the code is a bit complex at the moment due to the depth of the invocations. One more info I van give right now is that in debug mode that problem does not raise and the application works correctly! :-(

  • Hi,
    Your conclusion that the QList will copy your class is incorrect. It will seem like that on the outside, but QList will only push to pointer to the next position. A QList is buid up out of pointers, not real classes. Only when elements in the list are smaller in data containment then a pointer will it use the real elements. So in your case, the pointer will get shifted and no copy will be made.
    Btw the push_Back function is for STL compatibility, it's better to use the append function in QList.
    This said, it is probably not the cause of your crash. What do you mean with
    bq. when the Qt Gui terminates its normal thread loop

    The QtGui thread is run in the QApplication, so when that stops, all events are halted. There may only be one thread with Gui elements active and that is ALWAYS the main thread. So when you have a GUI application, you may not and expect no event handling or proper code execution when the QApplication is closed.
    So, like SGaist says, please some code. Maybe the class definition??

Log in to reply