First, I am not good at English, so I use a translator.
This code is the code that supports move semantic in vector.
A code that creates a single vector and inserts a Test object into the push_back() method.
The result of this code is that every time a Test object is added because of a push_back() method, the move constructor should be called, right?
But the compiler calls the move constructor only when new objects are inserted, and the old ones call the copy constructor.
Why is this happening? Am I missing something?
#include <iostream>
#include <vector>
using namespace std;
class Test
{
public:
Test(int data1, int data2) :data1(data1), data2(data2)
{
cout << "Normal Constructor" << endl;
}
Test(const Test& src)
{
cout << "Copy Constructor" << endl;
this->data1 = src.data1;
this->data2 = src.data2;
}
Test(Test&& rhs)
{
cout << "Move Constructor" << endl;
this->data1 = rhs.data1;
this->data2 = rhs.data2;
rhs.data1 = 0;
rhs.data2 = 0;
}
Test& operator=(const Test& src)
{
if (this == &src)
return *this;
cout << "Copy assignment operator" << endl;
this->data1 = src.data1;
this->data2 = src.data2;
return *this;
}
Test& operator=(Test&& rhs)
{
if (this == &rhs)
return *this;
cout << "Move assignment operator" << endl;
this->data1 = rhs.data1;
this->data2 = rhs.data2;
rhs.data1 = 0;
rhs.data2 = 0;
return *this;
}
private:
int data1, data2;
};
int main()
{
vector<Test> vec;
for (int i = 0; i < 5; i++)
{
cout << "Iteration " << i << endl;
vec.push_back(Test(100, 100));
cout << endl;
}
}