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

心不动则不痛 提交于 2019-12-09 09:53:49

问题


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?


回答1:


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.




回答2:


Can someone give me a simple example of a class which shouldn't be moved bit-by-bit?

By the standard, doing a memcpy on any class that isn't a POD in C++03 (or trivially copyable in C++11) would qualify. memcpying non-PODs (or non-trivially copyable) invokes undefined behavior; therefore an actual copy (or in C++11, move) constructor must be used.

So std::vector itself applies, since it is not a POD type (and in C++11, it's not trivially copyable).



来源:https://stackoverflow.com/questions/11165924/c-automatic-vector-reallocation-invokes-copy-constructors-why

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!