tags:

views:

217

answers:

1

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:

  • allocate the new buffer
  • copy the prefix of the old buffer (0 - index of insertion)
  • construct the new element in the new buffer
  • copy the suffix of the old buffer (index - end)
  • call destructor on all items in old buffer
  • deallocate old buffer

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?

+3  A: 

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.

Alexander Gessler
Yes, I did. I was seeing the <int> specialization. Thanks!
Flawe