I have the following code:
#include
using std::cin; using std::cout; using std::endl;
#include
using std::vector;
class Quote {
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