c++ - vector push_back calling copy_constructor more than once? -
The way I behave vector push_back, I'm a bit suspicious, with the following snippet I hope the copy constructor is only Will apply twice, but the output otherwise suggests whether it is a vector internal restructuring that results in this behavior.
Output:
Inside the copy with my_int = 0, copy the underlying copy = 0 into my_int = 0 My_int = 1
with square mant {private: int my_int; Public: Ment (): my_int (0) {cout & lt; & Lt; "Inside the default" & lt; & Lt; Endl; } Mant (Constant Ment and X): M_Int (XIIIIT) {COAT & LT; & Lt; "My_int =" & lt; & Lt; X.my_int & lt; & Lt; Endl; } Zero Set (Consult & End) {my_int = x; }} Vector & lt; Myint & gt; Myints; Mentor X; Myints.push_back (x); X.set (1); Myints.push_back (x);
What happens:
-
X
is inserted through thepush_back
. A copy is made: The newly created element begins with the argument.my_int
is taken as zero because the default constructor ofx
has started it. -
The second element
push_back
'd; The vector needs to be reallocated until it reaches.
As a conductor builder, not defined formant
1 ; Copy creator is chosen; The first element is copied to the new allocated memory (itsmy_int
is still zero ... so copy constructormy_int
as0
Again) and thenx
is copied to start another element (with first step 1). This time thex
is set tomy_int
, and that the copy producer tells us the output.
The total amount of the call is three, it may be different from an implementation because initial capacity may vary, however, two calls are minimal.
You can reduce the quantity of copies by reserving more memory in advance - that is, the capacity of the vector is high so that the relayation is unnecessary:
myints.reserve (2) ; // Now two elements can be allocated without.
In addition, when you insert, you can delete copies:
myints.emplace_back (0);
This creates a new element "an element" - is a varied template and therefore can take an arbitrary amount of arguments that, after that - without copies or moves - element creator for.
1 Because it is a user-declared counter constructor.
Comments
Post a Comment