PDA

View Full Version : Check has created with new



wirasto
11th December 2009, 06:33
How to check object has created with new ? I tried like this, but not work :(




Tahede *_tahede;
//_tahede=new Tahede(this);
if (_tahede)
{
qDebug() << "Created before";

_tahede->exec();
}
else
{
qDebug() << "Create now";

_tahede=new Tahede(this);
_tahede->exec();
}


Application output window only give me message...

Created before
QDialog::exec: Recursive call detected

toreo
11th December 2009, 06:53
If you intend there to be only one Tahede instance in your program, please look at the singleton pattern. If you want to have a delayed construction of a member variable, you need to initialize it to 0 first. Perhaps the following would work (might not compile verbatim, inline code for a brief example):


class MyObject : public QObject
{
public:
MyObject() : _tahede(0) {}

void doExec() {
tahede()->exec();
}

protected:
Tahede* tahede() {
if(!_tahede)
_tahede = new Tahede(this);
return _tahede;
}

private:
Tadede* _tahede;
};

wirasto
11th December 2009, 07:16
Thanks for your replay. But, how delete that object. I modified your code sample...



void doExec() {
tahede()->exec();
}

void doDelete() {
delete _tahede;
}

protected:
void changeEvent(QEvent *e);

Tahede* tahede() {
if(!_tahede)
{
_tahede = new Tahede(this);

qDebug() << "Create now";
}
else
{
qDebug() << "Created before";
}
return _tahede;
}

private:
Tahede* _tahede;





void Dialog::on_pushButton_clicked()
{
doExec();
}

void Dialog::on_pushButton_2_clicked()
{
doDelete();
}



After I deleted with doDelete() function, and doExec() again, Application output still give me message "Created before" and my application crash :( What's wrong ?

dbzhang800
11th December 2009, 07:27
when you delete your object, your had better:

delete _tahede;
_tahede = 0;

faldzip
11th December 2009, 11:34
or use a QPointer whis sets automagicaly itself to 0 when the object is deleted:


private:
QPointer<Tadede> _tahede;
};

cafu
16th March 2010, 16:02
Hi There,

i have a small problem while casting from QPointer<T> to QPointer<ChildT>

I tried this.

QPointer<T> tObject=new T();
//QPointer<ChildT> childtObject=(QPointer<T>)tObjec;// this does not work;
QPointer<ChildT> childtObject=(ChildT*)(T*)tObjec;// this work;