-
allocator::destroy
I'm working on a vector-type class, but I'm having trouble with my remove function.
I'm using std::allocator to allocate memory for my vector, and I'm trying to use the destroy member to delete an element like this:
Code:
void destroy_test(iterator todelete){
allocated_memory.destroy(todelete);
}
but if i try this on a vector that contains the ints 1, 2, 3, 4
Code:
vec.destroy_test(vec.begin());
it still prints out 1, 2, 3, 4?
-
Presumably, your destroy doesn't actually remove the data from the vector itself, which leaves the data in there.
--
Mats
-
But why does this happen? Shouldn't allocator::destroy call the object's destructor?
http://msdn2.microsoft.com/en-us/library/83f353w9.aspx
-
And does the destructor remove it from the vector?
--
Mats
-
alright so i tried using std::string and destroy seems to work on it. guess i had to find out the hard way that built-in types don't have destructors... :mad:
-
So you're accessing destructed strings now? That's undefined behaviour.
-
No, I just used that function to illustrate my problem. I would never try something like that :D
-
I don't think you follow what I meant: When destroying something WITHIN a vector, it doesn't mean that the vector element itself is removed - just that the object the vector held in itself is destroyed. Which, as CornedBee is saying, is undefined behaviour [and it will most often actually work fine for small test-cases, but crash badly when in a more complex setup].
To remove something from within a vector, you need to use a function like vector::erase().
--
Mats
-
Okay, but I think you also misunderstand the purpose of my post. It wasn't to create my own erase function to use on std::vector, but instead an erase function for my own class that is supposed to mimic a vector (it was a chapter exercise). Sorry if I wasn't being clear about that in the beginning...