Back to slide -- Keyboard shortcut: 'u'        next -- Keyboard shortcut: 'n'          references/rval-1.cc - Illustration of Rvalue references - in contrast to other kinds of references.Lecture 2 - slide 19 : 29
Program 1

// Illustrates Rvalue references in relation to Lvalue references. DOES NOT COMPILE.

#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

  string& s3 = sf("AA", 'U');          // Error: Cannot bind an Rvalue to Lvalue reference

  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&& s6 = s1;                    // Error: Cannot bind an Lvalue to an Rvalue reference.

  string&& s7 {"AU"};                  // Perfect to bind "AU" to an Rvalue refence.
  cout << "s7: " << s7 << endl;        // s7: AU

  string&& s8 {s7};                    // Error: Cannot bind a string Lvalue to to an Rvalue.

  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
}