C ++: Automatic redistribution of vectors causes copies of constructors? What for?

I read C ++ Primer, 3rd Ed (Lippman and Lajoie), and he says that when a vector needs to be redistributed to create space for more elements added using push_back() , the elements will be copied to a new space, and then the destructor is called old elements. I am confused why this is necessary - why data cannot be copied bit-by-bit? I believe the answer is related to dynamic memory allocation, but my current line of reasoning is that even if vector elements process dynamic memory, the data actually stored in the elements will be pointers, which means that bitwise copying will keep the location. which they point to and will not present any problems. I can see how reassigning the dynamically allocated memory pointed to by these elements will be a problem, as this will invalidate the pointers, but, as far as I can tell, there would be no reason to redefine the vector.

Can someone give me a simple example of a class that cannot be moved in half?

+6
source share
2 answers

Here is probably the simplest (but far-fetched) example:

 class foo { int i; int* pi; // always points to i }; 

Here the copy constructor will save the invariant that pi points to i . The compiler itself could not independently determine these relations, so you need to call the copy constructor.

+7
source

Can someone give me a simple example of a class that cannot be moved in half?

By standard, making memcpy for any class that is not a POD in C ++ 03 (or trivially copyable in C ++ 11) will qualify. memcpy ing non-POD (or non-trivially copied) causes undefined behavior; therefore, you must use the constructor of the actual copy (or in C ++ 11, move).

So std::vector is applied because it is not a POD type (and in C ++ 11 it cannot be trivially copied).

+4
source

Source: https://habr.com/ru/post/918809/


All Articles