fork download
  1. #include <iostream>
  2. #include <utility>
  3. #include <string>
  4. using namespace std;
  5.  
  6. void foo(const string&) { cout << "const string&" << endl; }
  7.  
  8. void foo(string&&) { cout << "string&&" << endl; }
  9.  
  10. void bar(string&& x) { foo(x); }
  11. // Use one of the following versions to get intended results
  12. //void bar(string&& x) { foo(std::move(x)); }
  13. //void bar(string&& x) { foo(std::forward<string>(x)); }
  14.  
  15. template<typename T>
  16. void barbar(T&& x) { foo(std::forward<T>(x)); }
  17.  
  18. int main() {
  19. cout << \"42\"" << endl;
  20. foo("42"); // string&&
  21.  
  22. cout << "» const string a" << endl;
  23. const string a = "Hello";
  24. foo(a); // const string&
  25. foo(std::move(a)); // const string& -> not string&& because a is const
  26.  
  27. cout << "» string b" << endl;
  28. string b = "World";
  29. foo(b); // const string&
  30. foo(std::move(b)); // string&&
  31. //bar(b); //cannot bind rvalue reference of type ‘string&&’ to lvalue of type ‘string’
  32. bar(std::move(b)); // const string& -> why not string&& ?
  33.  
  34. cout << "» forwarding reference" << endl;
  35. barbar(b); // const string&
  36. barbar(std::move(b)); // string&&
  37.  
  38. return 0;
  39. }
Success #stdin #stdout 0s 4544KB
stdin
Standard input is empty
stdout
» "42"
string&&
» const string a
const string&
const string&
» string b
const string&
string&&
const string&
» forwarding reference
const string&
string&&