简体   繁体   English

std :: vector和copy构造函数

[英]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 ? 为什么这段代码会调用类X的复制构造函数6次 (using g++ 4.7.2 STL) (使用g ++ 4.7.2 STL)

Please, I'd like to know it precisely what happens under hood with this particular STL. 拜托,我想知道它引擎盖下发生的正是这个特别STL。

When you insert x with push_back() , the memory is reallocated eventually to make room for the new element. 当您使用push_back()插入x时,最终会重新分配内存以为新元素腾出空间。 The already inserted members must then be copied around using the copy constructor X(const X&) . 然后必须使用复制构造函数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&) 至少在前三个push_back()阻止重新分配,因此,只有三次调用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). 在第一个push_back之前,向量的容量(适合其分配的空间的元素数)为0.因此,当您执行第一个push_back时,它为1个项目分配空间并调用复制构造函数(第一个调用) 。

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). 第二个push_back再次调用复制构造函数(第三次调用)。

Now you have a capacity of 2 and tell it to add another item. 现在你的容量为2,并告诉它添加另一个项目。 So it has to allocate more space and copy the items to the new space (4th and 5th calls). 因此,它必须分配更多空间并将项目复制到新空间(第4和第5次调用)。 Then the third push_back calls the copy constructor again (6th call). 然后第三个push_back再次调用复制构造函数(第6次调用)。

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. 正如其他人所指出的,您可以使用reserve,它将预先分配空间,从而无需重新分配,从而调用复制构造函数。

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. 正确的答案是std::vector是使用doubleling-array实现的(参见: http//en.wikipedia.org/wiki/Dynamic_array ),它调用的复制构造函数约为2 * N倍。

For example, for N = 100,000 it calls the copy constructor 231,071 times. 例如,对于N = 100,000它调用复制构造函数231,071次。 As it has been pointed out, the number of reallocations can be reduced by calling to v.reserve() . 正如已经指出的那样,通过调用v.reserve()可以减少重新分配的次数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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