Search code examples
c++qtvectorqlistview

Error deleting a pointer in a vector


I am getting trouble trying to delete a pointer that is owned by a vector. In my application I have a QListView, and I store new items based on a vector of pointers. This is the declaration:

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

I simplified it, but it is an attribute of a class. To add new items I use this code:

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 );
}

This works just fine. Now I am trying to add a delete button which deletes the current index on the QListView. This is the code I made so far:

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

For what I searched on StackOverflow, the line

delete this->item[deleteIndex];

should work, but I am getting an application crash every time I press the delete button. Without that line the button works fine, the problem is that I am not deallocating the memory used by that item.

EDIT: I already made a question related to the same problem.
[Error using Qt and unique pointers

Now I am wondering if I am trying to delete the pointer two times, and thats why I am getting the error. The problem is that my knowledge about c++ and qt is not very high.


Solution

  • You're actually deleting a second time the QStandardItem that was at this index. Indeed, as you can see in the following extract from the Qt doc of the QStandardItemModel's function setItem

    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.

    the QStandardItemModel manages any QStandardItem you would pass it, and thus you should never try to delete these.

    As a rule of thumb, when you're unsure, check the Qt documentation for any function where you pass a QObject. If it says it take ownership, then never delete it.