Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Destructor called in foreach loop iteration in QList derived class



  • Hi All,
    I'm doing a fairly basic QT excercise/tutorial the involves the following class:

    class BookingList: public QList<Booking*>
    {
    public:
        BookingList();
        ~BookingList();
        int roomsAvailable(QDate d);
        bool vacancy(QDate a, QDate d);
        Booking* addBooking(Person c, QDate a, QDate d, Person* g1, Person* g2);
        void deleteAll();
    
        int NO_OF_ROOMS;
    };
    

    However something unexpected (at least to me) happens when I use a foreach loop in the roomsAvailable() function:

    BookingList::~BookingList()
    {
        qDeleteAll(*this);
        this->clear();
        qDebug()<<"destructor called...";
    }
    
    int BookingList::roomsAvailable(QDate d)
    {
       int bookedRooms = 0;
        foreach(Booking* b, *this)
        {
            if(b->booked(d))
                bookedRooms++;
        }
    
        return NO_OF_ROOMS - bookedRooms;
    }
    

    Each iteration of this loop will call the destructor directly above, which is something I really didn't expect. Is it because, in dereferencing "this" I'm sending a copy to foreach(), which subsequently gets destroyed? Is this correct? Should I avoid this because it involves a lot of copying?

    I replaced the foreach with a normal for loop and the destructor is not called (until the end of the program).


  • Lifetime Qt Champion

    Deriving from a container is for sure no good idea. Make it a member.

    I replaced the foreach with a normal for loop and the destructor is not called (until the end of the program).

    Take a look at the code of the macro and you will see why this happens: https://code.woboq.org/qt5/qtbase/src/corelib/global/qglobal.h.html#1044 (hint: your container will be detached/copied)



  • @Christian-Ehrlicher Thanks for the feedback and link. I've been working from a book called "An introduction to design patterns in C++ with QT" by Ezust and Ezust. They have a handful of examples where they derive from a QList<>. I'm personally not a fan of doing it that way, but its just surprising that they do it so liberally if it's bad practice.


Log in to reply