fork download
  1. #include <iostream>
  2. #include <algorithm>
  3.  
  4. class Matrix4 {
  5. float* m;
  6. public:
  7. Matrix4() : m(new float[16]) {}
  8. Matrix4(const Matrix4& other) : m(new float[16])
  9. { std::copy(other.m, other.m+16, m); std::cout << "\ncopy"; }
  10. Matrix4(Matrix4&& other) : m(other.m) { other.m = 0; std::cout << "\nmove"; }
  11. ~Matrix4() { delete[] m; }
  12. Matrix4& operator+= (const Matrix4& other)
  13. {
  14. for(auto i = 0; i < 16; ++i) { m[i] += other.m[i]; }
  15. return *this;
  16. }
  17. };
  18.  
  19. Matrix4 operator+ (Matrix4 l /* move from temporary*/, const Matrix4& r)
  20. {
  21. std::cout << "\noperator+(Matrix4, const Matrix4&)";
  22. return std::move(l += r); // move explicitly, because += returns lvalue reference
  23. }
  24.  
  25. Matrix4 operator+ (const Matrix4& l, Matrix4&& r)
  26. {
  27. std::cout << "\nnoperator+(const Matrix4&, Matrix4&&)";
  28. return std::move(r += l); // move explicitly
  29. }
  30.  
  31. int main()
  32. {
  33. Matrix4 a;
  34. std::cout << "\nMatrix4 b(a+a)";
  35. Matrix4 b(a+a);
  36. std::cout << "\nMatrix4 c(a + a + a)";
  37. Matrix4 c(a + a + a);
  38. std::cout << "\nMatrix4 d(a + (a + a))";
  39. Matrix4 d(a + (a + a));
  40. }
Success #stdin #stdout 0s 3016KB
stdin
Standard input is empty
stdout
Matrix4 b(a+a)
copy
operator+(Matrix4, const Matrix4&)
move
Matrix4 c(a + a + a)
copy
operator+(Matrix4, const Matrix4&)
move
operator+(Matrix4, const Matrix4&)
move
Matrix4 d(a + (a + a))
copy
operator+(Matrix4, const Matrix4&)
move
noperator+(const Matrix4&, Matrix4&&)
move