c++ - vector push_back calling copy_constructor more than once? -



c++ - vector push_back calling copy_constructor more than once? -

i bit confused way vector push_back behaves, next snippet expected re-create constructor invoked twice, output suggest otherwise. vector internal restructuring results in behaviour.

output:

inside default within re-create my_int = 0 within re-create my_int = 0 within re-create my_int = 1 class myint { private: int my_int; public: myint() : my_int(0) { cout << "inside default " << endl; } myint(const myint& x) : my_int(x.my_int) { cout << "inside re-create my_int = " << x.my_int << endl; } void set(const int &x) { my_int = x; } } vector<myint> myints; myint x; myints.push_back(x); x.set(1); myints.push_back(x);

what happens:

x inserted via push_back. 1 re-create occurs: newly created element initialized argument. my_int taken on 0 because xs default constructor initialized so.

the sec element push_back'd; vector needs reallocate memory since the internal capacity reached. no move constructor implicitly defined myint1 re-create constructor chosen; first element copied newly allocated memory (its my_int still zero... re-create constructor shows my_int 0 again) , x copied initialize sec element (as first in step 1.). time x has my_int set 1 , that's output of re-create constructor tells us.

so total amount of calls three. might vary 1 implementation initial capacity might different. however, 2 calls minimum.

you can cut down amount of copies by, in advance, reserving more memory - i.e. higher vectors capacity reallocation becomes unnecessary:

myints.reserve(2); // 2 elements can inserted without reallocation.

furthermore can elide copies when inserting follows:

myints.emplace_back(0);

this "emplaces" new element - emplace_back variadic template , can hence take arbitrary amount of arguments forwards - without copies or moves - elements constructor.

1 because there user-declared re-create constructor.

c++ stdvector

Comments

Popular posts from this blog

xslt - DocBook 5 to PDF transform failing with error: "fo:flow" is missing child elements. Required content model: marker* -

mediawiki - How do I insert tables inside infoboxes on Wikia pages? -

Local Service User Logged into Windows -