Levi
Levi

Reputation: 151

Wt 3 memory deallocation

Mostly it's clear where memory is deallocated in wt 3(very explicit in wt 4) but in this case I don't understand the logic.

The below function content sets a container for my wt 3 application. Everything works fine but could anyone explain how is (or should this) returned _content be handled?

_content is kept as private class data.

Wt::WContainerWidget* _content;

Function content() handles container

Wt::WContainerWidget* web::content() 
{
    if (_content == 0) {
       _content = new Wt::WContainerWidget(root()); //memory allocation
    }
    return _content; //allocated memory gets returned
}

later this is used like:

void web::sayhi()
{
    content()->addWidget(new Wt::WBreak());
    content()->addWidget(new Wt::WText("hello world"));
}

How is this suppose to delete/handle allocated memory returned by content()

Upvotes: 0

Views: 89

Answers (2)

RockinRoel
RockinRoel

Reputation: 308

If you use this form of the constructor:

_content = new Wt::WContainerWidget(root());

Then the widget is added to root() as a child, so it's owned by root(). _content is actually non-owning in this case.

So, when the WApplication is destroyed, the root() and every child of root() is destroyed with it.

This is equivalent to doing this in Wt 4:

_content = root()->addWidget(std::make_unique<Wt::WContainerWidget>());

or shorter (since Wt 4.0.1):

_content = root()->addNew<Wt::WContainerWidget>();

Upvotes: 3

Jordi Adell
Jordi Adell

Reputation: 91

You should store content as a variable member stored by value, instead of a pointer. If you must keep content as a pointer then you may want to explore the use of smart pointers (std::unique_ptr or std::shared_ptr)

Upvotes: 0

Related Questions