I am trying to understand move constructor and written following code
#include<iostream>
#include<string>
using namespace std;
class mystring
{
string s;
public:
mystring(const string& x):
s(x)
{
}
mystring(const mystring& x)
{
cout<<"Copy called"<<endl;
s = x.s;
}
mystring(const mystring&& x)
{
cout<<"Move Called"<<endl;
s = x.s;
}
mystring& operator+(const mystring& x)
{
cout<<"+ operator"<<endl;
s = s+x.s;
return *this;
}
};
int main()
{
string a = "Hello ";
string b = "World ";
mystring a1(a);
mystring b1(b);
mystring c = mystring(a1+b1);
}
I am expecting call of move constructor on the result rValue of a1+b1 but i am seeing only copy constructor is being called. Am i missing something?
gcc --version
gcc (Ubuntu 7.4.0-1ubuntu1~18.04.1) 7.4.0
Edited after HolyBlackCat's answer:
#include<iostream>
#include<string>
using namespace std;
class mystring
{
string s;
public:
explicit mystring(const string& x):
s(x)
{
cout<<"ctor called"<<endl;
}
mystring(const mystring& x)
{
cout<<"Copy called"<<endl;
s = x.s;
}
mystring(mystring&& x)
{
cout<<"Move Called"<<endl;
s = std::move(x.s);
}
mystring operator+(const mystring& x) const
{
cout<<"+ operator"<<endl;
return mystring(s+x.s);
}
};
int main()
{
string a = "Hello ";
string b = "World ";
mystring a1(a);
mystring b1(b);
mystring c(a1+b1) ;
}
The move constructor is still not being called:
ctor called ctor called + operator ctor called