You are not logged in.

Dear visitor, welcome to QtForum.org. If this is your first visit here, please read the Help. It explains in detail how this page works. To use all features of this page, you should consider registering. Please use the registration form, to register here or read more information about the registration process. If you are already registered, please login here.

1

Wednesday, August 26th 2009, 1:30pm

Memory management & a weird constructor

Hi everyone,
I'm new to Qt and while reading the book "C++ GUI Programming with Qt 4" I found the following piece of code:

Source code

1
2
3
4
5
6
7
8
9
10
11
GoToCellDialog::GoToCellDialog(QWidget *parent)
: QDialog(parent)
{
setupUi(this);

QRegExp regExp("[A-Za-z][1-9][0-9]{0,2}");
lineEdit->setValidator(new QRegExpValidator(regExp, this));

connect(okButton, SIGNAL(clicked()), this, SLOT(accept()));
connect(cancelButton, SIGNAL(clicked()), this, SLOT(reject()));
}

So, regExp is an object of the type QRegExp created locally (on stack), which is latter passed to QRegExpValidator constructor as refence! Why doesn't it cause an error? Function ends and stack is cleaned long before Validator is executed for the first time, so the reference can point to some random data! What is going on?
Cheers,
Kisielewski

2

Sunday, August 30th 2009, 8:48am

If you look at the source of QRegExpValidator:

(gui/widgets/qvalidator.h)

Source code

1
2
3
4
5
6
...
private:
    Q_DISABLE_COPY(QRegExpValidator)

    QRegExp r;
...


(gui/widgets/qvalidator.cpp)

Source code

1
2
3
4
5
6
...
QRegExpValidator::QRegExpValidator(const QRegExp& rx, QObject *parent)
    : QValidator(parent), r(rx)
{
}
...


I think this makes clear what's going on:)
Cheers!

3

Sunday, August 30th 2009, 10:54am

OK, so entire QRegExp is copied to QRegExpValidator object, that makes sense.
Thanks & cheers :),
Kisielewski