Why vector hold a class type will call the copy constructor one more time when push_back()?

前端 未结 2 2063
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-23 04:50

I have the following code:

#include 
using std::cin; using std::cout; using std::endl;
#include 
using std::vector;

class Quote {
         


        
2条回答
  •  [愿得一人]
    2021-01-23 05:18

    When the push_back is called at the 2nd time, reallocation happened. (More precisely it happens when the new size() is greater than capacity().) Then the old underlying storage of the vector will be destroyed and the new one will be allocated, and elements need to be copied to the new storage, which cause the copy constructor to be called.

    You can use reserve to avoid reallocation. e.g.

    vector basket;
    basket.reserve(2);
    basket.push_back(Quote("0-201-82470-1", 50));
    basket.push_back(Quote("0-201-82XXXXX", 30)); // no reallocation here
    

提交回复
热议问题