problem with deleting pointer
i have a class with :
in some function addLCD() i’m declaring it:
- lcd->setGeometry(5, 43, 75, 30);
- lcd->display(30);
in other function hideLCD() i’m hiding it:
- if(lcd->isVisible())
- lcd->hide();
- // delete lcd; // that doesn't work!
in third function begin() i’m using these functions in that way:
- if(ifBegun==true)
- hideLCD(); // here i wanna clear memory
- else
- ifBegun=1;
- addLCD();
The problem is with deleting pointer! When i’m using this , it shows me segmentation fault. Without comment in hideLCD() it’s working fine.
bq. Debugger throws me an error:
Program received signal SIGSEGV, Segmentation fault.
0×08055c48 in QWidget::testAttribute (this=0×81eac38, attribute=Qt::WA_WState_Visible) at /usr/include/qt4/QtGui/qwidget.h:1025
1025 return data->widget_attributes & (1<<attribute);
Why is he doing that?
5 replies
You created it like this:
so this (instance of your class) is the parent of lcd, so that will delete it when it is deleted (out of scope or deleted by you or deleted by parent if if has one)
If you delete it yourself and then Qt parent-child mechanisms try to delete it again you can get seg-fault errors.
Am i sure? I’m ensuring that by:
- ifBegun=0
in constructor.
If it is a valid pointer to a valid widget? Well, If I can hide it so I think it’s valid.
Destroy on close flags? Where can i set that?
I’m using that lcd on slot (slot is calling only by clicking some button).
I’m setting
- lcd->display(number);
and those two functions.
And for understanding: if I would like to clean up this pointer, i have to call it in destructor of my class, right?
Hi,
first of all:
if ifBegun a bool or an int? if it’s a bool initialise it by ifBegun=false and set ifBegun=true inmstead of 1, otherwise don’t compare it to false.
second, the pointer you use is lcd.
To make it safer, you could use QPointer<QLCDNumber>, which sets itself to 0 if the object is destroyed and which is always 0 as initial state.
If you always want to destroy the object when you hide it, you can delete it directly, no need of first hiding it. To make it a bit safer, call lcd->deleteLater() which will delete the object in the next event loop run.
You must log in to post a reply. Not a member yet? Register here!




