Page 1 of 1

wxObject concept

Posted: Tue Apr 15, 2008 6:16 pm
by Qasim
Hi, just wondering if I derive a class from wxObject , and then new it, will this be automatically deleted when my frame is deleted ???
I mean some thing like this

Code: Select all

class MyObj : public wxObject
{
public:
int x;
Data* myData;
}
then somewhere in a frame i do

Code: Select all

void MyFrame::MyFrameFunc(){
MyObj* obj = new MyObj();
obj->myData = new Data;
}
now will this be referenc counted in Myframe and will be deleted automatically when frame is destroyed ??? or I have got a completely wrong concept of it ?
Any help will be appreciated.

Posted: Tue Apr 15, 2008 11:56 pm
by JimFairway
Hi,

Unless wxWidgets has automatic garbage collection (which I haven't come across yet),
the object will persist in memory (without anything pointing to it), after the frame is deleted because the frame does not 'own' the object and you are creating it on the heap using:

Code: Select all

MyObj* obj = new MyObj();
Why it won't automatically delete the object is that the widget library doesn't know if you passed that pointer to another widget that still exists.

To get rid of the object, you could delete it in your MyFrame destructor.
Or you could declare the object in your MyFrame class:

Code: Select all

class myFrame : public wxFrame {
...
MyObj obj;
...
}
Hope that helps,

Jim

Re: wxObject concept

Posted: Wed Apr 16, 2008 5:40 am
by Utensil
Hi,

Here is just some further explanation on JimFairway's answer which I agree with:
Qasim wrote: now will this be referenc counted in Myframe and will be deleted automatically when frame is destroyed ??? or I have got a completely wrong concept of it ?
Please take a look at the folowing sequence, which explained the concept of how reference-counting works:

Code: Select all

MyObj* obj = new MyObj(); //Now the reference count is 1

MyObj* obj_ref1 = obj; //Now the reference count is 2

//If you quit without deleting them now, the reference count is still above 0, so it won't be deleted by wxObject at all.

delete obj_ref1; //Now the reference count is reduced to 1, still above 0, so the real object(not the pointer) won't be deleted. 

func(obj); //You can still use obj

delete obj; //Now the reference count is reduced to 0, the real object will be deleted from the heap
So you have to take care of the deletion yourself. As for the obj->mydata, you have to take care of its deletion in the destructor of MyObject.

BTW, shouldn't obj->mydata be private? How can you "new" it outside the class MyObject? The "new" work should be done in the constructor of MyObject.

Regards,

Utensil

Posted: Wed Apr 16, 2008 10:11 am
by Qasim
thanks for all the help, I understand now.