fork download
  1. #include <iostream>
  2.  
  3. struct A {
  4. struct APlusA {
  5. APlusA(const A&a_, const A&b_) : a(a_), b(b_) {}
  6. const A &a;
  7. const A &b;
  8.  
  9. operator A() const {
  10. std::cout << "Creating temporary A" << std::endl;
  11. return A(a.val + b.val);
  12. }
  13. };
  14.  
  15. A(int val_) : val(val_) {}
  16. friend APlusA operator+(const A&a, const A&b) { return APlusA(a,b); }
  17. friend std::ostream &operator<<(std::ostream &s, const A &a) { return s << a.val;}
  18.  
  19. A& operator=(const APlusA &apa) {
  20. if (this == &apa.a) {
  21. std::cout << "Performing in-place operator" << std::endl;
  22. val += apa.b.val;
  23. }
  24. else
  25. {
  26. *this = static_cast<A>(apa);
  27. }
  28. }
  29.  
  30. int val;
  31. };
  32.  
  33. int main() {
  34. A a(4), b(5), c(6);
  35. std::cout << a+b << std::endl; //Temporary created
  36. a = b+c; //Temporary created
  37. a = a+b; //No temporary - inplace operation
  38. std::cout << a << std::endl;
  39. return 0;
  40. }
  41.  
Success #stdin #stdout 0s 3140KB
stdin
Standard input is empty
stdout
Creating temporary A
9
Creating temporary A
Performing in-place operator
16