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

只谈情不闲聊 提交于 2019-12-04 03:31:49

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.

Nicol Bolas

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).

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