Meir Meir - 3 years ago 86
C++ Question

Vector erase function deleting wrong object

I have a vector declared as:

vector<Curve> workingSet;


Curve is a class I've created that contains a string "name" and an array of structs, dynamically allocated by the constructor.

I have a loop that is supposed to delete 2 (out of 4) items from the vector.

vector<Curve>::iterator it = workingSet.begin();

//remove tbi's children from the working set
for ( ; it != workingSet.end();){
if (it->thisName == tbi.childAName ||it->thisName == tbi.childBName)
it= workingSet.erase(it);
else
++it;
}


When the debugger reaches the .erase(it) call I can see that the 'it' iterator is pointing to curve 2 in the vector. This is good; I want curve 2 to be removed from the vector.

I'm then taken by the debugger to the destructor (I have a breakpoint there), which presumably should be destructing curve 2. But when I look at the 'this' watch, I can see that the curve being destructed is curve 4! The destructor then proceeds to 'delete[]' the array in the object, as required and sets the array pointer to NULL.

When the debugger returns to the program, having completed the erase() call, I can see that vector 2 has been removed from the array and curve 4 is still there. Curve 4's array pointer still points to the same location as before, but the memory has been deallocated and the array contains garbage.

Can anyone suggest why curve 4 is being messed with?

N.b. (1) There is a copy constructor for the curve class, which does a 'deep' copy.
N.b. (2) There is more to the class/program than I've mentioned here

Btw, the array pointers in curves 2 and 4 point to different locations and contain different values, according to the debugger.

Edit: I've now implemented copy assignment. Now the correct item seems to be being erased from the vector, but the wrong destructor is still being called! However, when the debugger returns to the array curve 4 is still intact.

Xeo Xeo
Answer Source

When an item is erased from the vector, all elements behind it are shifted towards the front to fill the empty space. If your compiler doesn't support move yet, it's done by copying all the elements, and the last item in the vector, which is now copied to the item before it, is a duplicate and is getting deleted.

At least that's how it should work.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download