使用Qt和唯一指针时出错 [英] Error using Qt and unique pointers

查看:154
本文介绍了使用Qt和唯一指针时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在开发一个随机应用程序的接口。在界面中,我有一个 QListView ,它有三个相关的按钮。第一个是添加,它在窗口小部件上添加一个新项目,此按钮工作正常。问题出在清除按钮:

I am currently working on an interface for an random application. In the interface I have a QListView, which have three buttons related to it. The first one is add, which adds a new item on the widget, this button works fine. The problem comes with the clear button:

void NeuralNetwork::on_clearButton_clicked() {
    this->model.get()->clear();
    this->item.clear();
}

,因为您看到模型和项目都是此类的属性。它们被声明为:

as you see both model and item are attributes of this class. They are declared as this:

std::unique_ptr<QStandardItemModel> model = unique_ptr<QStandardItemModel>(new QStandardItemModel());
vector<unique_ptr<QStandardItem>> item;

最初我使用正常的指针,但是当我在互联网上搜索时,人们推荐使用唯一的指针处理内存管理。

Initially I was using normal pointers, but as I searched on the internet, people were recommending using unique pointers to handle memory management.

我认为

this->model.get()

但我不知道,没有智能指针的经验。注意,程序没有得到生成错误,它工作正常,直到我按下清除按钮的界面,然后程序崩溃:

but I don't know exactly, since I have no experience with smart pointers. Note that the program doesn't get build errors, it works fine until I press the clear button on the interface, then the program crashes:


The program has unexpectedly finished.


推荐答案

由于QStandardItemModel拥有标准项目的所有权。因此,当您将标准项与唯一的指针相关联时,您将获得双删除。

Be carefull, as QStandardItemModel has ownership of standard items. Therefore you would get a double delete when you associated a standard item with a unique pointer.

一般来说,使用Qt,不需要使用唯一指针已经拥有其子女的所有权。

In general, with Qt you don't need to use unique pointers, as parents already have ownership of their children.

这篇关于使用Qt和唯一指针时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆