I'm reading C++ Primer, 3rd Ed (Lippman and Lajoie) and it's saying that when a vector needs to be reallocated in order to make space for more elements added with push_back()
, the elements are copy-constructed in the new space and then the destructor is called on the old elements. I'm confused about why this is necessary - why can't the data just be copied bit-for-bit? I assume that the answer has to do with dynamic memory allocation, but my current line of reasoning is that even if the vector elements handle dynamic memory, the data actually stored in the elements will be pointers, meaning bitwise copying will preserve the location they point to and won't present any problems. I can see how re-locating the dynamically-allocated memory that the elements point to would be a problem, since it would invalidate the pointers, but as far as I can tell the vector re-location would have no reason to do that.
Can someone give me a simple example of a class which shouldn't be moved bit-by-bit?
If a copy constructor, copy-assignment operator, move constructor, move-assignment operator, or destructor is explicitly declared, then: No move constructor is automatically generated. No move-assignment operator is automatically generated.
emplace_back():This function can directly insert the object without calling the copy constructor.
The default copy constructor will copy all members – i.e. call their respective copy constructors. So yes, a std::vector (being nothing special as far as C++ is concerned) will be duly copied.
Here's probably the simplest (but rather contrived) example:
class foo
{
int i;
int* pi; // always points to i
};
Here, the copy constructor would maintain the invariant that pi
points to i
. The compiler itself wouldn't be able to figure out this relationship on its own, hence the need to call the copy constructor.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With