Strange problem with vectors.

Posted by Catalin Dumitru on Stack Overflow See other posts from Stack Overflow or by Catalin Dumitru
Published on 2011-01-13T16:32:29Z Indexed on 2011/01/13 16:53 UTC
Read the original article Hit count: 350

Filed under:
|
|
|

I have a really strange problem with stl vectors in which the wrong destructor is called for the right object when I call the erase method if that makes any sense.
My code looks something like this:

 for(vector<Category>::iterator iter = this->children.begin(); iter != this->children.end(); iter++)
    {
        if((*iter).item == item)
        {
            this->children.erase(iter);
            return;
        }
        -------------------------
    }

It's just a simple function that finds the element in the vector which has some item to be searched, and removes said element from the vector. My problem is than when the erase function is called, and thus the object which the iterator is pointing at is being destroyed, the wrong destructor is being called. More specific the destructor of the last element in the vector is being called, and not of the actual object being removed. Thus the memory is being removed from the wrong object, which will still be an element in the vector, and the actual object which is removed from the vector, still has all of it's memory intact.
The costructor of the object looks like this:

Category::Category(const Category &from)
{
    this->name = from.name;
    for(vector<Category>::const_iterator iter = from.children.begin(); iter != from.children.end(); iter++)
        this->children.push_back((*iter));

    this->item = new QTreeWidgetItem;
}

And the destructor

Category::~Category()
{
    this->children.clear();
    if(this->item != NULL)
    {
        QTreeWidgetItem* parent = this->item->parent();
        if(parent != NULL) parent->removeChild(this->item);
        delete this->item;
    }
}

© Stack Overflow or respective owner

Related posts about c++

Related posts about qt