I am trying to understand the behavior of object copying and object move when containers are involved. Here is a sample code i wrote.
#include<memory>
#include<iostream>
#include<vector>
using namespace std;
class X{
int val;
public:
X(int i):val(i){cout<<"constructor X"<< val <<endl;}
X(){cout<<"constructor X"<< val <<endl;}
X(const X &a) {cout<<"copy constructor X"<< val <<endl;}
X(X &&a) {cout<<"move constructor X"<< val <<endl;}
~X(){cout<<"Distructor X"<< val << endl;}
X& operator = (X a){ cout<<"Assignment operator"<<endl; return a;}
void do1(){cout<<"Do"<<endl;}
};
vector<X> container_copy(){
vector<X> a1(10);
return a1;
}
main(){
vector<X> b;
vector<X> a = container_copy(); //#1 .
b = a; // #2
cout<<"Done"<<endl;
}
here is the sample output i got using
constructor X0
constructor X0
constructor X0
copy constructor X0
copy constructor X0
copy constructor X0
Done
Distructor X0
Distructor X0
Distructor X0
Distructor X0
Distructor X0
Distructor X0
Here is my queries.
Why is the move constructor not called for statement marked #1
Why is the copy constructor called instead of assignment operator for #2
I am using following command for compiling under gcc
g++ <file_name>.cpp --std=c++11