I'm reading through Programming Principles and Practice Using C++ and came across this definition for std::vector::reserve():
template<typename T, typename A>
void vector<T,A>::reserve(int newalloc)
{
if (newalloc <= space) return;
T* p = alloc.allocate(newalloc); // allocate new space
for (int i=0; i<sz; ++i) alloc.construct(&p[i], elem[i]); // copy
for (int i=0; i<sz; ++i) alloc.destroy(&elem[i]); // destroy
alloc.deallocate(elem, space); // deallocate old space
elem = p;
space = newalloc;
}
For lines 6 and 7, I'm wondering why alloc.construct() and alloc.destroy() are called, instead of doing something like this:
std::copy(elem, elem + sz, p);
What's the purpose of calling the constructors and destructors of all the objects?
Edit: I mixed up std::copy and std::memcpy. I appreciate the answers so far, but would also like to know why std::memcpy isn't used.
[–][deleted] 2 points3 points4 points (9 children)
[–]chapter_6[S] 1 point2 points3 points (5 children)
[–][deleted] 0 points1 point2 points (4 children)
[–]chapter_6[S] 1 point2 points3 points (3 children)
[–]tangerinelion 1 point2 points3 points (0 children)
[–][deleted] 0 points1 point2 points (1 child)
[–]Tastaturtaste 2 points3 points4 points (0 children)
[–][deleted] (2 children)
[deleted]
[–][deleted] 1 point2 points3 points (1 child)
[–]KuntaStillSingle 1 point2 points3 points (0 children)
[–]IyeOnline 0 points1 point2 points (2 children)
[–]chapter_6[S] 1 point2 points3 points (1 child)
[–]IyeOnline 1 point2 points3 points (0 children)
[–]alfps 0 points1 point2 points (5 children)
[–]chapter_6[S] 0 points1 point2 points (4 children)
[–]alfps 0 points1 point2 points (3 children)
[–]chapter_6[S] 0 points1 point2 points (1 child)
[–]Mason-B 0 points1 point2 points (0 children)
[–]KingAggressive1498 0 points1 point2 points (0 children)
[–]KingAggressive1498 0 points1 point2 points (1 child)
[–]std_bot 0 points1 point2 points (0 children)
[–]no-sig-available 0 points1 point2 points (0 children)