c++ - 删除 vector 中的指针时出错

标签 c++ qt vector qlistview

我在尝试删除 vector 拥有的指针时遇到麻烦。在我的应用程序中,我有一个 QListView,并且我基于指针 vector 存储新项目。这是声明:

private:
vector<QStandardItem *> item; 
QStandardItemModel* model = new QStandardItemModel();

我简化了它,但它是一个类的属性。要添加新项目,我使用以下代码:

this->item.push_back(new QStandardItem());
for (unsigned long i = 0; i != this->item.size(); ++i) {
    this->item[i]->setCheckable( true );
    this->item[i]->setCheckState( Qt::Checked );
    this->item[i]->setText( "Current " + QString::number(i) );
    this->model->setItem( i, this->item[i] );
    ui->listView->setModel( model );
}

这工作得很好。现在我尝试添加一个删除按钮来删除 QListView 上的当前索引。这是我迄今为止编写的代码:

QModelIndex index = ui->listView->currentIndex();
int deleteIndex = index.row();
this->model->removeRow(deleteIndex);
delete this->item[deleteIndex];
this->item.erase(this->item.begin() + deleteIndex);

对于我在 StackOverflow 上搜索的内容,该行

delete this->item[deleteIndex];

应该可以,但每次按下删除按钮时,我都会遇到应用程序崩溃的情况。如果没有该行,按钮可以正常工作,问题是我没有释放该项目使用的内存。

编辑:我已经提出了与同一问题相关的问题。
[Error using Qt and unique pointers

现在我想知道我是否尝试删除指针两次,这就是我收到错误的原因。问题是我对c++和qt的了解不是很高。

最佳答案

您实际上是在第二次删除位于该索引处的QStandardItem。事实上,正如您在 QStandardItemModel's function setItem 的 Qt 文档的以下摘录中看到的那样

Sets the item for the given row and column to item. The model takes ownership of the item. If necessary, the row count and column count are increased to fit the item. The previous item at the given location (if there was one) is deleted.

QStandardItemModel 管理您将传递给它的任何 QStandardItem,因此您永远不应该尝试删除它们。

根据经验,当您不确定时,请检查 Qt 文档以了解传递 QObject 的任何函数。如果它说它拥有所有权,那么永远不要删除它。

关于c++ - 删除 vector 中的指针时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25648704/

相关文章:

c++ - 带有 Visual Studio 2005 的 volatile unsigned __int64 行为异常

c++ - 为什么 boost::bind 存储传入类型的参数而不是函数期望的类型?

c++ - "Can' t load OpenGL extension [glBindBuffer] in function IntGetProcAddress”Qt中OpenCV异常

带有 QSslSocket 的 Qt 连接不正确

c++ - 如何在一个 vector 中存储具有不同数据类型的对象

r - 将命名向量转换为 R 中的列表

r - 将二进制向量转换为二进制矩阵

c++ - 将指向成员函数的指针作为 void* 函数的参数传递

qt - 将 Qt 模型绑定(bind)到现有数据结构

c++ - OpenSSL:无法通过 FTPS 检索 LIST