General and Desktop

컨테이너에 적재된 객체를 편리하게 삭제하기

by makersweb posted Sep 18, 2019
?

단축키

Prev이전 문서

Next다음 문서

ESC닫기

크게 작게 위로 아래로 댓글로 가기 인쇄

QList나 QVector등과 같은 컨테이너에 new로 생성된 객체가 적재되어 있을때 어느 시점에는 삭제(delete)를 해줘야 한다.

 

그럴때 qDeleteAll함수를 사용하면 매우 유용한데 이 함수는 C++의 delete 연산자를 사용하여 컨테이너의 모든 항목을 삭제해준다.

 

void qDeleteAll(ForwardIterator begin, ForwardIterator end)

void qDeleteAll(const Container & c)

 

간단한 예제 코드이다.

#include <QtAlgorithms> // qDeleteAll함수 관련 헤더 포함

QList<Employee *> list;
list.append(new Employee());
list.append(new Employee());

qDebug() << "count: " << list.count();

qDeleteAll(list.begin(), list.end());

qDebug() << "count: " << list.count(); // 컨테이너의 항목을 제거하지 않는다는 것에 유의하자.

list.clear(); // 컨테이너의 항목을 모두 지운다.

qDebug() << "count: " << list.count(); 

 

다른 예를 들면 QVBoxLayout에 자식 위젯들이 있다고 가정했을때 다음과 같이 사용할 수 있다.

QGroupBox * box = new QGroupBox;
box->setObjectName("PushButtonBox");

QPushButton *button1 = new QPushButton();
QPushButton *button2 = new QPushButton();
QPushButton *button3 = new QPushButton();

QVBoxLayout *vlayout = new QVBoxLayout;
vlayout->addWidget(button1);
vlayout->addWidget(button2);
vlayout->addWidget(button3);

box->setLayout(vlayout);

box->show();

qDebug() << "before: " << box->children();
qDebug() << "count: " << box->children().count();

qDeleteAll(box->children());

qDebug() << "after: " << box->children();
qDebug() << "count: " << box->children().count(); // 여기선 안심하자.

 

TAG •

Articles

4 5 6 7 8