I am trying to learn the new features in C++11. And I am testing the following code in XCode.
class CClass
{
std::string s;
public:
CClass()
{
cout<<"Default Constructor"<<endl;
}
CClass(const std::string v) :s(v) {
cout<<"Constructor"<<endl;
}
CClass(const CClass& other): s(other.s) {
cout<<"Copy Constructor"<<endl;
}
CClass(CClass&& a) noexcept
{
cout<<"Move Constructor"<<endl;
s = std::move(a.s);
}
CClass& operator = (const CClass& other)noexcept
{
cout<<"Copy Assignment"<<endl;
if(this != &other)
{
s = other.s;
}
return *this;
}
CClass& operator = (CClass&& other) noexcept
{
cout<<"Move Assignment"<<endl;
if(this != &other)
{
s = std::move(other.s);
}
return *this;
}
void Print()
{
cout<<s<<endl;
}
};
void test()
{
std::vector<CClass> v;
CClass x("hello");
//CClass y("buffallo");
//v.push_back(x);
cout<<"--------------------"<<endl;
v.emplace_back("uiuiu");
cout<<"--------------------"<<endl;
for(int i = 0; i < v.size(); i++)
{
v[i].Print();
}
}
When I uncomment the push back I get the following result:
Constructor
Copy Constructor
--------------------
Constructor
Move Constructor
--------------------
hello
uiuiu
Otherwise, if I comment it, I get:
Constructor
--------------------
Constructor
--------------------
uiuiu
My question is why is move constructor not being called in second case. It is only being called in the first case when vector is initially not empty.
Aucun commentaire:
Enregistrer un commentaire