0

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.

Dimitrios Menounos
  • 545
  • 1
  • 6
  • 17
  • Does this answer your question? [What is move semantics?](https://stackoverflow.com/questions/3106110/what-is-move-semantics) – Jay Jan 20 '21 at 04:12
  • 2
    Wait, what do you want exactly? I wouldn't expect `get1` to move `_s`. – user202729 Jan 20 '21 at 04:15
  • @user202729 Why not? The signature of get1() returns by value and the string class has a move constructor. – Dimitrios Menounos Jan 20 '21 at 04:26
  • 1
    Obviously, **one would not expect that returning a string in get1() would clear the source string.** Automatic move will only occurs when returning local objet *(that would get destroyed otherwise)*. As far as I know the result of get2() is not guarantee to be what you observe because of small string optimization. – Phil1970 Jan 20 '21 at 04:35
  • Fine, fine. let me check. – user202729 Jan 20 '21 at 04:36
  • @Phil1970 You are right. The member variable (_s) is an lvalue while move semantics work with rvalues. – Dimitrios Menounos Jan 20 '21 at 04:53

1 Answers1

0

Phil1970 answered this in a comment above.

Move semantics work with rvalues. The _s member variable is apparently an lvalue and that is why get1() results in a copy instead of a move.

Dimitrios Menounos
  • 545
  • 1
  • 6
  • 17