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;
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
user2267860
source
share