fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. struct A {
  5. std::string s;
  6. A(const std::string& s) : s(s) {}
  7. A(const A& o) : s(o.s) { std::cout << "move failed!\n"; }
  8. A(A&& o) : s(std::move(o.s)) {}
  9. A& operator=(const A&) { std::cout << "copy assigned\n"; return *this; }
  10. A& operator=(A&& other) {
  11. std::cout << s << " " << other.s << endl;
  12. s = std::move(other.s);
  13. std::cout << "move assigned\n";
  14. std::cout << s << " " << other.s << endl;
  15. return *this;
  16. }
  17. };
  18.  
  19. A f(A a) { return a; }
  20.  
  21. struct B : A {
  22. B(const std::string& s) : A(s) { }
  23. std::string s2;
  24. int n;
  25. // implicit move assignment operator B& B::operator=(B&&)
  26. // calls A's move assignment operator
  27. // calls s2's move assignment operator
  28. // and makes a bitwise copy of n
  29. };
  30.  
  31. int main()
  32. {
  33. A a1("foo"), a2("bar");
  34. std::cout << "Trying to move-assign A from rvalue temporary\n";
  35. a1 = f(A("asda")); // move-assignment from rvalue temporary
  36. std::cout << "Trying to move-assign A from xvalue\n";
  37. a2 = std::move(a1); // move-assignment from xvalue
  38.  
  39. std::cout << "Trying to move-assign B\n";
  40. B b1("foo"), b2("bar");
  41. std::cout << "Before move, b1.s = \"" << b1.s << "\"\n";
  42. b2 = std::move(b1); // calls implicit move assignment
  43. std::cout << "After move, b1.s = \"" << b1.s << "\"\n";
  44. }
Success #stdin #stdout 0s 3232KB
stdin
Standard input is empty
stdout
Trying to move-assign A from rvalue temporary
foo asda
move assigned
asda foo
Trying to move-assign A from xvalue
bar asda
move assigned
asda bar
Trying to move-assign B
Before move, b1.s = "foo"
bar foo
move assigned
foo bar
After move, b1.s = "bar"