Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: Automatic vector reallocation invokes copy constructors? Why?

Tags:

c++

stdvector

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?

like image 498
user1476176 Avatar asked Jun 23 '12 01:06

user1476176


People also ask

Are move constructor automatically generated?

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.

Does Emplace_back call copy constructor?

emplace_back():This function can directly insert the object without calling the copy constructor.

What happens if you use the default copy constructor for vector?

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.


1 Answers

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.

like image 180
jjlin Avatar answered Oct 28 '22 17:10

jjlin