| references/rval-1-compilable.cc - The compilable parts of the program from above. | Lecture 2 - slide 19 : 29 Program 2 |
// The compilable parts of the previous program.
#include <iostream>
#include <string>
using namespace std;
// A function that returns a string - an r-value.
string sf (string s, char ch){
return s + ch;
}
int main () {
string s1 {"AAU"}; // s1 is initialized to "AAU"
string& s2{s1} ; // s2 is a reference to s1.
s2[0] = 'B'; // Mutating s2 affects s1:
cout << s1 << endl; // BAU
const string& s4 {sf("AA", 'U')}; // OK to bind an Rvalue to a const reference, however...
cout << "s4: " << s4 << endl; // s4: AAU
string&& s5 {sf("AA", 'U')}; // It is problably most natural to bind the result of the sf call to an Rvalue reference.
// Move constructor of string in use.
cout << "s5: " << s5 << endl; // s5: AAU
string&& s7 {"AU"}; // Perfect to bind "AU" to an Rvalue refence.
cout << "s7: " << s7 << endl; // s7: AU
string&& s9 {move(s7)}; // We can cast s7 to an rvalue. Misleadingly named move, see The C++ Prog. Lang page 194-195.
cout << "s9: " << s9 << endl; // s9: AU
}