vector push_back calling copy_constructor more than once?

后端 未结 5 1213
刺人心
刺人心 2020-11-29 10:23

I am a bit confused with the way vector push_back behaves, with the following snippet I expected the copy constructor to be invoked only twice, but the output suggest otherw

5条回答
  •  不知归路
    2020-11-29 11:11

    This depends on how much memory was reserved to an object of type std::vector. It seems that when push_back was first executed there was allocated memory only for one element. When the second time push_back was called the memory was reallocated to reserve memory for the second element. In this case the element that is already in the vector is copied in the new place. And then the second element is also added.

    You could reserve enough memory yourself that to escape the second call of the copy constructor:

    vector myints;
    myints.reserve( 2 );
    

提交回复
热议问题