fork(1) download
  1. #include <iostream>
  2. #include <algorithm>
  3.  
  4. class Base
  5. {
  6. protected:
  7. std::string str;
  8. void* ptr;
  9.  
  10. void swap(Base &a, Base &b)
  11. {
  12. using std::swap;
  13. swap(a.ptr, b.ptr);
  14. swap(a.str, b.str);
  15. }
  16.  
  17. public:
  18. Base(std::string str, void* ptr) : str(str), ptr(ptr) {}
  19. Base(Base&& other) : str(), ptr(nullptr) {swap(other, *this);}
  20.  
  21. virtual ~Base() {}
  22. };
  23.  
  24. class Derived : public Base
  25. {
  26. protected:
  27. void* ptr2;
  28.  
  29. void swap(Derived &a, Derived &b)
  30. {
  31. using std::swap;
  32. swap(a.ptr2, b.ptr2);
  33. }
  34.  
  35. public:
  36. Derived(std::string str, void* ptr, void* ptr2) : Base(str, ptr), ptr2(ptr2) {}
  37.  
  38. /** copy-swap idiom*/
  39. Derived(Derived&& other) : Base(std::forward<Derived>(other)), ptr2(nullptr) {swap(other, *this);}
  40.  
  41. void Print() {std::cout<<Base::str<<" "<<(char*)Base::ptr<<" "<<(char*)ptr2<<"\n";}
  42. };
  43.  
  44. int main()
  45. {
  46. char str[] = "100";
  47. char str2[] = "200";
  48.  
  49. Derived d = Derived("100", &str[0], &str2[0]);
  50.  
  51. Derived d2 = std::move(d);
  52. d2.Print();
  53.  
  54. //d.Print(); //Prints nothing.. it was moved..
  55.  
  56. return 0;
  57. }
Success #stdin #stdout 0s 3432KB
stdin
Standard input is empty
stdout
100  100  200