简体   繁体   中英

std::vector and copy constructors

vector<X> 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 6 times ? (using g++ 4.7.2 STL)

Please, I'd like to know it precisely what happens under hood with this particular STL.

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&)

您可以使用矢量预留来预先在矢量中创建空间,以加快向矢量添加元素以及阻止其发生。

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.

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() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM