user4386938
user4386938

Reputation:

Why does a vector have to move its data members when reallocating

Assuming that a vector contains an array internally of std::aligned_storage instances that actually contain elements of the type the vector is templated on if the aligned_storage instance is in use.

When the vector has to allocate a new block of memory and move all its elements, why does it invoke the move constructor of each element in use and then destroy the old element? Why not just copy over all the bytes byte by byte and just delete the old array without calling destructors? This would make the new array an exact copy of the old array without the overhead of moving and destroying elements.

Maybe I'm a little tired and am missing something really basic. But I cannot think of a reason why this would not work.

Upvotes: 2

Views: 437

Answers (1)

Bob
Bob

Reputation: 160

It would not be safe to merely copy the bytes. Imagine, for example, that your object has two members, p and d, and p is a pointer that points to d. If you just copy the bytes, you'd copy the value of p that points to the old location of d, which has been destroyed.

This is a simple example, but in general, the reason for C++ constructors, destructors, copy and move constructors, is to allow your object to be "smarter" than just a sequence of bytes would be. Member variables have meaning, and that meaning is understood by your code, not by the compiler.

Upvotes: 7

Related Questions