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

前端 未结 2 2090
慢半拍i
慢半拍i 2021-02-15 06: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_b

相关标签:
2条回答
  • 2021-02-15 07:15

    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.

    0 讨论(0)
  • 2021-02-15 07:16

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

    0 讨论(0)
提交回复
热议问题