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

前端 未结 2 2089
慢半拍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.

提交回复
热议问题