gpt4 book ai didi

c++ - 将 std::unique_ptr.get() 作为参数传递给 addWidget()

转载 作者:行者123 更新时间:2023-11-30 00:48:51 25 4
gpt4 key购买 nike

我正在尝试将 QWidget 指针参数 (plot2) 传递给 QtaddWidget(QWidget * T,. ..) 将指向 QWidget 的指针作为其第一个参数的函数。如果我传递原始指针 plot2,我会按预期获得两个并排面板。

原始指针版本

    plot1 = new QWidget;
plot2 = new QWidget;

gridLayout = new QGridLayout(gridLayoutWidget);
...
gridLayout->addWidget(plot1, 1, 1, 1, 1);
gridLayout->addWidget(plot2.get(), 1, 2, 1, 1);

但是,如果我使用 std::unique_ptr 版本的 plot2 并通过 std::unique_ptr(plot2) 传递指针,如下面的代码片段所示,面板与 plot2 相关联的文件在编译器没有提出任何投诉的情况下丢失。

智能指针版本

    plot1 = new QWidget;
auto plot2 = std::unique_ptr<QWidget>(new QWidget);

gridLayout = new QGridLayout(gridLayoutWidget);
...
gridLayout->addWidget(plot1, 1, 1, 1, 1);
gridLayout->addWidget(plot2.get(), 1, 2, 1, 1); // this panel goes missing

我试过使用 std::shared_ptr 但结果还是一样。

当然,如果我 release()plot2 相关联的 std::unique_ptr 如下,那么我的理解是什么从此以后,我不再使用智能指针版本的 plot2

使用 std::unique_ptr.release()

    plot1 = new QWidget;
auto plot2 = std::unique_ptr<QWidget>(new QWidget);

gridLayout = new QGridLayout(gridLayoutWidget);
...
gridLayout->addWidget(plot1, 1, 1, 1, 1);
gridLayout->addWidget(plot2.release(), 1, 2, 1, 1);

你能想出如何让它工作吗?

最佳答案

来自文档(强调我的):

Adds item at position row, column, spanning rowSpan rows and columnSpan columns, and aligns it according to alignment. If rowSpan and/or columnSpan is -1, then the item will extend to the bottom and/or right edge, respectively. The layout takes ownership of the item.

当您添加该小部件时,您不再拥有它,因此存储在 std::unique_ptr 中然后调用 release 是完全合理的。这实际上比原始指针版本更可取,就好像某些东西在你将它添加到布局之前抛出异常,内存将被自动回收。

关于c++ - 将 std::unique_ptr.get() 作为参数传递给 addWidget(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30482973/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com