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
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With