c++memory-managementwt

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()


Solution

  • 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>();