Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
645 views
Welcome To Ask or Share your Answers For Others

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...