the_naive the_naive - 3 months ago 12
C++ Question

Does QList clear function call clears the memories of dynamically allocated objects that are stored in the QList?

So I have class called

AppointmentSchedule
which is of the following type:

namespace Ui {
class AppointmentSchedule;
}

class AppointmentSchedule : public QWidget
{
Q_OBJECT

public:
explicit AppointmentSchedule(QWidget *parent = 0);
~AppointmentSchedule();
Ui::AppointmentSchedule *ui;
};


The
ui
of this class consists of two objects of type
QLabel
and two objects of type
QDateTimeEdit
. In an external class, I need to have a
QList
of dynamically allocated objects of type
AppointmentSchedule
. I will append the dynamically allocated objects in the
QList
similar to the following way.

QList<AppointmentSchedule*> scheduleList;

foreach (QDate date, dates)
{
AppointmentSchedule * newSchedule = new AppointmentSchedule(this);//Allocation of memory
QDateTime sDateTime(date, QTime(8, 0, 0));
newSchedule->ui->appointmentStartDateTimeEdit->setDateTime(sDateTime);
QDateTime eDateTime(date, QTime(8, 15, 0));
newSchedule->ui->appointmentEndDateTimeEdit->setDateTime(eDateTime);
scheduleList.append(newSchedule);
}


If I call the
clear()
function of the
QList
like this:

scheduleList.clear();


Will it deallocate all the memory I have allocated?

Thanks.

Answer

Will it deallocate all the memory I have allocated?

No, clear() only remove all items from the list. In your case this items are pointers on AppointmentSchedule objects.

As you set parent for AppointmentSchedule objects, this objects wiil be deleted when their parent will be destroyed. That's why there is no memory leak in your case.

Comments