I am trying to understand how move semantics work in particular with the standard string. My primary concern is how to expose a string member variable of a class through a method, for example a getter.
So I made this example program.
#include <iostream>
#include <string>
using namespace std;
class Object {
string _s;
public:
Object(string s) : _s(s) {}
string get1() { return _s; }
string get2() { return move(_s); }
void print() { cout << "'" << _s << "'" << endl; }
};
int main() {
Object obj("0123456789ABCDEF_");
string s1 = obj.get1();
obj.print(); // prints '0123456789ABCDEF_'
string s2 = obj.get2();
obj.print(); // prints ''
}
Both methods get1() and get2() return by value.
I expected the get1() to automatically move the internal _s, however as you can see that is not the case. The get2() on the other hand makes the move, though this is expected as I explicitly ask for it.
So the question is why get1() does not move _s.