Wt 3 memory deallocation

Wt 3 memory deallocation

本文关键字:deallocation memory Wt      更新时间:2023-10-16

主要是很明显在wt 3中对内存的位置(在wt 4中非常明确),但是在这种情况下,我不了解逻辑。

以下功能内容为我的WT 3应用程序设置一个容器。一切都很好,但是谁能解释如何(或应该这样)返回_ content?

_content作为私人类数据。

Wt::WContainerWidget* _content;

功能内容()句柄容器

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

以后使用的是:

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

该如何删除/处理由content()

返回的分配的内存

如果使用这种形式的构造函数:

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

然后小时候将小部件添加到root()中,因此由root()拥有。在这种情况下,_content实际上是不持有的。

所以,当WApplication被销毁时,root()root()的每个孩子都被它销毁。

这等同于在wt 4:

中这样做
_content = root()->addWidget(std::make_unique<Wt::WContainerWidget>());

或较短(自WT 4.0.1以来):

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

您应该将内容存储为一个由值而不是指针存储的变量成员。如果您必须将内容保留为指针,则可能需要探索智能指针的使用(std :: simelod_ptr或std :: shared_ptr)