fork download
  1. #include <iostream>
  2. #include <string>
  3.  
  4. std::string m_str;
  5.  
  6. void a(std::string&& other)
  7. {
  8. m_str = std::string(other); // this is wrong
  9. std::cout << "a: " << other << std::endl;
  10. // other is not EMPTY because inside the function,
  11. // the argument "other" got a name, and lost it's "rvalueness"
  12. }
  13.  
  14. void b(std::string&& other)
  15. {
  16. m_str = std::string(std::move(other));
  17. std::cout << "b: " << other << std::endl;
  18. // other is empty because std::move converted the lvalue "other" back to "rvalue"
  19. }
  20.  
  21. void c(std::string&& other)
  22. {
  23. m_str = std::string(std::forward<std::string>(other)); // other is empty as well.
  24. // because this function only accepts RValues, so std::forward does the same as std::move
  25. // if you call this function with a lvalue, you will get compile error.
  26. std::cout << "c: " << other << std::endl;
  27. }
  28.  
  29. //This functions accepts both rvalues and lvalues (other is a "forwarding reference")
  30. template<typename T>
  31. void d(T&& other)
  32. {
  33. m_str = std::string(std::forward<T>(other)); //If you use move here, other will always be empty.
  34. std::cout << "d: " << other << std::endl;
  35. // If other was an rvalue, other will be empty.
  36. // If other was an lvalue, other will NOT be empty.
  37. }
  38.  
  39. int main()
  40. {
  41. a(std::string("Hello World"));
  42. b(std::string("Hello World"));
  43. c(std::string("Hello World"));
  44. d(std::string("Hello World"));
  45. std::string lvalue = "Hello World";
  46. d(lvalue);
  47. return 0;
  48. }
Success #stdin #stdout 0s 3460KB
stdin
Standard input is empty
stdout
a: Hello World
b: 
c: 
d: 
d: Hello World