I have two functions taking in an rvalue reference to a string and adding something to that string. The first function returns the modified string and the second one has return type void.
Calling the first function on a string results in the original string being emptied, which is what I expected. However, calling the second function on a string brings it to its modified state as if the function were taking an lvalue reference.
Can someone please explain what is going on here? Is the compiler (VC++ configured for ISO C++ 14) doing some sort of "optimisation"?
#include <iostream>
#include <string>
using namespace std;
string g(string&& s)
{
s += " post g call";
return s;
}
void f(string&& s)
{
s += " post f call";
}
int main()
{
string s1("starting string");
string s2("starting string");
auto s1a = g(move(s1));
f(move(s2));
cout << s1 << endl;
cout << s1a << endl;
cout << s2 << endl;
}
s1 is empty string at the end of this program and s2 is "starting string post f call". I expected s2 to be empty as well.
Aucun commentaire:
Enregistrer un commentaire