Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need to delete QValidator manually?

Example code:

QDoubleValidator *validator = new QDoubleValidator();
myInputLineEdit->setValidator(validator);

// delete validator;

Note: myInputLineEdit is a QLineEdit pointer and will be deleted with its parent.

My question is, when should I delete validator, as it's manually created and setValidator() doesn't seem to take ownership of this pointer according to the documentation? If I don't delete it, will it be a memory leak?

I tried to delete it right after, like the commented code, and I noticed the validator of myInputLineEdit became 0 after that. So I think I may need to delete it after myInputLineEdit is deleted.

Another thought is, I could give validator a parent so it will be deleted along with its parrent, is this a good way to do that? What if there isn't a good candidator to be the parent?

Thanks

like image 595
vlursk Avatar asked Jan 22 '15 22:01

vlursk


2 Answers

I tried to delete it right after, like the commented code, and I noticed the validator of myInputLineEdit became 0 after that. So I think I may need to delete it after myInputLineEdit is deleted.

It's because QLineEdit uses QPointer internally, which tracks QValidator object if it was deleted.

and setValidator() doesn't seem to take ownership of this pointer according to the documentation

setValidator() indeed does not set parent of QValidator.

Another thought is, I could give validator a parent so it will be deleted along with its parrent, is this a good way to do that? What if there isn't a good candidator to be the parent?

You can either delete it manually, use smart pointers or do like @crayzeewulf said - set myInputLineEdit as parent (using QValidator constructor or setParent()). Parent takes care about deleting its children, so it is a way to go. Usually object to which validator is assigned is a good parent.

If I don't delete it, will it be a memory leak?

If you neither set a parent nor delete it, there will be a memory leak.

like image 106
mip Avatar answered Oct 20 '22 00:10

mip


Use mInputLineEdit as the parent of validator as in the example here. The destructor of a parent destroys all child objects (see this). This is the "qt way" of handling ownership trees.

like image 24
crayzeewulf Avatar answered Oct 19 '22 22:10

crayzeewulf