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

Categories

0 votes
660 views
in Technique[技术] by (71.8m points)

c++ - 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.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...