Project

General

Profile

Question Regarding Pointer/Memory Management with Wt

Added by Tom Thorogood about 12 years ago

I'm new to Wt, and am experiencing some leakage with a small app I've written. In many of the Wt examples, I see things like:

myWidget->addWidget(new WText(/*args*/);

Does Wt automatically manage and delete the anonymous widgets created this way, or are those just examples? Should I instead name and delete these myself?

A related question: is there a reason not to allocate these on the stack instead of the heap?

WText textWidget(/*args*/);

myWidget->addWidget(&textWidget);

Thanks for any help. I just want to make sure I don't wind up double-deleting, or under-managing pointers. I'm not sure how much ownership Wt takes for this sort of things.

-Tom


Replies (3)

RE: Question Regarding Pointer/Memory Management with Wt - Added by Rajeev Gajbhiye about 12 years ago

Hi,

When I started with Wt, I had exactly the same concern. What I discovered is that, an WObject can take ownership of another WObject, by associating parent child relationship. When the parent is deleted, so are the children. When you call myWidget->addWidget(innerWidget), the innerWidget becomes child of myWidget and hence, when myWidget is destructed, inner will be destructed too. In most of the cases you will not have to delete any widget explicitly. If you assign address of widget allocated on stack, then as soon as this object goes out the scope, the widget address will become invalid and container widget will misbehave. Even if you manage to keep the widget allocated on stack during entire life span of container, then the child widget will probably get deleted twice (parent widget is going to delete it too).

If I am wrong somewhere, please correct me.

Regards,

Rajeev.

RE: Question Regarding Pointer/Memory Management with Wt - Added by Wim Dumon about 12 years ago

Rajeev,

Tom,

That is correct. A parent will delete all of its children in its destructor (so those children will also delete their children). This means that when you give an object a parent, you transfer ownership of that object to the parent.

One more thing to notice: if a session is terminated (the user surfs away, closes the browser window, ping timeout, WApplication::quit() is called or the server is stopped), the root of the widget tree will be deleted, and thus all widget objects that you've put in the widget tree will be properly destroyed. In practice, this makes the memory management of Wt something that you hardly need to worry about - but you're right, you should know what Wt does with your objects.

Wt's widgets are not intended to be allocated on the stack, since 'delete' will be invoked on them.

Wim.

RE: Question Regarding Pointer/Memory Management with Wt - Added by Tom Thorogood about 12 years ago

Thanks for the explanations! Precisely what I was looking for.

    (1-3/3)