Flawe
Flawe

Reputation:

std::vector insert() reallocation

I was looking through the std::vector code and I found something I didn't quite get. When capacity < size() + 1 it needs to reallocate the buffer so it can insert the new element. What it does (as far as I've been able to extract from the code) is:

The prefix and suffix copy is done with memmove as far as I could see. Isn't memmove a pure binary copy of the data? It doesn't call the constructor of the elements, does it? What I was wondering is, why does the function call the destructor on the elements in the old buffer if the memory is just moved, not re-constructed in the new buffer?

Upvotes: 7

Views: 2286

Answers (1)

Alexander Gessler
Alexander Gessler

Reputation: 46607

I looked through the MSVC8 vector implementation - I can't see a memmove(). The previous vector elements are not moved, they're copied and their copy c'tor is called to copy them over to the new buffer (the buffer is allocated in a single allocation, elements are constructed using placement new).

Of course this is only the MSVC implementation, but it's how a vector should behave according to the standard.

However, using memmove is sometimes OK - for example for a std::vector<int> - and STL implementations are free to specialize for this case. You might have missed a template 'branch' reading the source code.

Upvotes: 5

Related Questions