My code is this:
#include <vector>
#include <iostream>
class A{
public:
A() = default;
A(const A& obj){
std::cout << "Copy c-tor" << std::endl;
}
A(A&& obj){
std::cout << "Move c-tor" << std::endl;
}
};
int main(int argc, char *argv[]){
std::vector<A> vA;
std::cout << "Copy ctor will be invoked: " << std::endl;
auto a = A();
vA.push_back(a);
std::cout << "Move ctor will be invoked: " << std::endl;
vA.push_back(A());
return 0;
}
I expected that there is one copy constructor invocation and one move constructor invocation. But the output has one two copy constructor call. As it is:
[amirreza@localhost copy]$ g++ copy.cpp
[amirreza@localhost copy]$ ./a.out
Copy ctor will be invoked:
Copy c-tor
Move ctor will be invoked:
Move c-tor
Copy c-tor
Why the copy ctor is called last time? Why the copy constructor is called twice?