fork(1) download
  1. #include <iostream>
  2. #include <string>
  3.  
  4. using namespace std;
  5.  
  6. class A
  7. {
  8. std::string m_Data;
  9.  
  10. public:
  11. explicit A(std::string data = "HEHE")
  12. : m_Data(std::move(data))
  13. {}
  14.  
  15. A(A&& other)
  16. {
  17. if (other.m_Data.empty())
  18. return;
  19.  
  20. m_Data = std::move(other.m_Data);
  21. }
  22.  
  23. A& operator=(A&& other)
  24. {
  25. if (m_Data.empty() || other.m_Data.empty())
  26. return *this;
  27.  
  28. m_Data = std::move(other.m_Data);
  29. return *this;
  30. }
  31.  
  32. const std::string& Data() const { return m_Data; }
  33. };
  34.  
  35. template<typename T>
  36. void MySwap(T& x, T& y)
  37. {
  38. T z = std::move(x);
  39. x = std::move(y);
  40. y = std::move(z);
  41. }
  42.  
  43. int main() {
  44. A a("A"), b("B");
  45. cout << "a=" << a.Data() << ", b=" << b.Data() << endl;
  46. MySwap(a, b);
  47. cout << "after MySwap: a=" << a.Data() << ", b=" << b.Data() << endl;
  48. return 0;
  49. }
Success #stdin #stdout 0s 3412KB
stdin
Standard input is empty
stdout
a=A, b=B
after MySwap: a=, b=A