Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::vector and copy constructors

Tags:

c++

gcc

stl

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.

like image 810
Cartesius00 Avatar asked Nov 15 '12 10:11

Cartesius00


2 Answers

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

like image 51
Olaf Dietsche Avatar answered Oct 30 '22 23:10

Olaf Dietsche


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.

like image 20
const_ref Avatar answered Oct 31 '22 00:10

const_ref