std::vector and copy constructors

前端 未结 4 1162
广开言路
广开言路 2020-12-19 09:04
vector v;
X x;
v.push_back(x); v.push_back(x); v.push_back(x);

Why this code calls the copy constructor of a class X

4条回答
  •  伪装坚强ぢ
    2020-12-19 09:28

    This is what happens:

    Before the first push_back, the capacity of the vector (the number of elements that fit in the space it has allocated) is 0. So when you do the first push_back, it allocates space for 1 item and calls the copy constructor (1st call).

    So now the capacity is one, and you tell it to add another item. So it has to allocate more space, in this case, space for one more item and copy the original items to the new space (2nd call). The second push_back calls the copy constructor again (3rd call).

    Now you have a capacity of 2 and tell it to add another item. So it has to allocate more space and copy the items to the new space (4th and 5th calls). Then the third push_back calls the copy constructor again (6th call).

    As others have pointed out, you can use reserve, which will allocate space upfront, avoiding the need to reallocate and thus, calls to the copy constructor.

提交回复
热议问题