fork download
  1. #include <iostream>
  2.  
  3. using std::cout;
  4. using std::endl;
  5.  
  6. class Foo {
  7. int m_i;
  8. public:
  9. Foo() : m_i(0) { cout << "Foo(@" << (void*)this << ") ctor" << endl; }
  10. Foo(int i) : m_i(i) { cout << "Foo(" << i << "@" << (void*)this << ") ctor" << endl; }
  11. ~Foo() { cout << "Foo(" << m_i << "@" << (void*)this << ") dtor" << endl;}
  12.  
  13. Foo(const Foo& rhs) : m_i(rhs.m_i) { cout << "Copying(" << m_i << "@" << (void*)&rhs << ") to Foo(@" << (void*)this << ")" << endl; }
  14. Foo& operator = (Foo rhs) { m_i = rhs.m_i; cout << "op=ing(" << m_i << "@" << (void*)&rhs << ") to Foo(@" << (void*)this << ")" << endl; }
  15.  
  16. Foo operator + (Foo rhs) {
  17. Foo result(m_i);
  18. cout << (void*)(&result) << " = " << (void*)this << " + " << (void*)(&rhs) << endl;
  19. result.m_i += rhs.m_i;
  20. return result;
  21. }
  22.  
  23. operator int() const { return m_i; }
  24. };
  25.  
  26. class Bar {
  27. int m_i;
  28. public:
  29. Bar() : m_i(0) { cout << "Bar(@" << (void*)this << ") ctor" << endl; }
  30. Bar(int i) : m_i(i) { cout << "Bar(" << i << "@" << (void*)this << ") ctor" << endl; }
  31. ~Bar() { cout << "Bar(" << m_i << "@" << (void*)this << ") dtor" << endl;}
  32.  
  33. Bar(const Bar& rhs) : m_i(rhs.m_i) { cout << "Copying(" << m_i << "@" << (void*)&rhs << ") to Bar(@" << (void*)this << ")" << endl; }
  34. Bar& operator = (const Bar& rhs) { m_i = rhs.m_i; cout << "op=ing(" << m_i << "@" << (void*)&rhs << ") to Bar(@" << (void*)this << ")" << endl; }
  35.  
  36. Bar operator + (const Bar& rhs) {
  37. Bar result(m_i);
  38. cout << (void*)(&result) << " = " << (void*)this << " + " << (void*)(&rhs) << endl;
  39. result.m_i += rhs.m_i;
  40. return result;
  41. }
  42.  
  43. operator int() const { return m_i; }
  44. };
  45.  
  46. int main(int argc, const char** argv) {
  47. {
  48. Foo a(5), b(10), c;
  49. c = a + b;
  50. cout << (int)c << endl;
  51. }
  52.  
  53. cout << endl << "Now let's do it properly." << endl << endl;
  54.  
  55. {
  56. Bar a(5), b(10), c;
  57. c = a + b;
  58. cout << (int)c << endl;
  59. }
  60.  
  61. return 0;
  62. }
Success #stdin #stdout 0s 2856KB
stdin
Standard input is empty
stdout
Foo(5@0xbfd2f27c) ctor
Foo(10@0xbfd2f280) ctor
Foo(@0xbfd2f284) ctor
Copying(10@0xbfd2f280) to Foo(@0xbfd2f288)
Foo(5@0xbfd2f28c) ctor
0xbfd2f28c = 0xbfd2f27c + 0xbfd2f288
op=ing(15@0xbfd2f28c) to Foo(@0xbfd2f284)
Foo(15@0xbfd2f28c) dtor
Foo(10@0xbfd2f288) dtor
15
Foo(15@0xbfd2f284) dtor
Foo(10@0xbfd2f280) dtor
Foo(5@0xbfd2f27c) dtor

Now let's do it properly.

Bar(5@0xbfd2f290) ctor
Bar(10@0xbfd2f294) ctor
Bar(@0xbfd2f298) ctor
Bar(5@0xbfd2f29c) ctor
0xbfd2f29c = 0xbfd2f290 + 0xbfd2f294
op=ing(15@0xbfd2f29c) to Bar(@0xbfd2f298)
Bar(15@0xbfd2f29c) dtor
15
Bar(15@0xbfd2f298) dtor
Bar(10@0xbfd2f294) dtor
Bar(5@0xbfd2f290) dtor