Why are constructors and copies of vector initialization?

I am learning C ++ and I am looking at STL containers. I have a lot of questions, but I think this may go first. Consider this class and its vector.

class A {
   int i;
   // A(const A&);
public:

   A(int i) : i(i) {cout << "consting " << i << endl;}
   A(const A& ot) : i(ot.i) {cout << "copying " << i << endl;}

};

int main () {
   vector<A> v1 = {A(1),A(2),A(3),A(4)};
   vector<A> v2(1,A(5));
   vector<A> v3;
   v3.push_back(A(6));
}

gives me a way out

consting 1
consting 2
consting 3
consting 4
copying 1
copying 2
copying 3
copying 4
consting 5
copying 5
consting 6
copying 6

Obviously, he builds and copies everyone A.

Is there any way to prevent this. I mean, how can I avoid an extra copy and just build Ainto a vector. Is it possible. If not, can someone explain why? Thank.

EDIT: Just to complete, sake push_backdoes the same

+5
source share
2 answers

, std::vector. , , std::array :

std::array<A, 4> a1 = {{A(1),A(2),A(3),A(4)}};

stdout:
consting 1
consting 2
consting 3
consting 4
+4

, . , emplace_back :

vector<A> v1;
v1.reserve(4);
v1.emplace_back(1);
v1.emplace_back(2);
v1.emplace_back(3);
v1.emplace_back(4);

, :

consting 1
consting 2
consting 3
consting 4
+3

All Articles