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&)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With