std::vector and copy constructors

前端 未结 4 1161
广开言路
广开言路 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:20

    When you insert x with push_back(), the memory is reallocated eventually to make room for the new element. The already inserted members must then be copied around using the copy constructor X(const X&).

    If you insert

    v.reserve(3);
    

    reallocation is prevented for at least the first three push_back()s and, as a result, there will be only three calls to X(const X&)

    0 讨论(0)
  • 2020-12-19 09:25

    The right answer is that std::vector is implemented using the doubling-array (see: http://en.wikipedia.org/wiki/Dynamic_array) and it calls approximately 2 * N times the copy constructor.

    For example, for N = 100,000 it calls the copy constructor 231,071 times. As it has been pointed out, the number of reallocations can be reduced by calling to v.reserve().

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-19 09:29

    You can use vector reserve to create space in the vector before hand to speed up adding elements to a vector as well as stopping this from happening.

    0 讨论(0)
提交回复
热议问题