fork download
  1. #include <iostream>
  2.  
  3. class FooException
  4. {
  5. int id;
  6. public:
  7. FooException(int n) : id(n) {}
  8. int getId() const { return id; }
  9. };
  10.  
  11. class Foo;
  12.  
  13. class Bar
  14. {
  15. friend Foo;
  16. int val;
  17. Bar() : val(0) {}
  18. Bar(const int v) : val(v) {}
  19. Bar(const Bar& b) : val(b.val) {}
  20. int getVal() const { return val; }
  21. };
  22.  
  23. class Foo
  24. {
  25. Bar *p;
  26. int id;
  27. static int num() {
  28. static int v = 0;
  29. return v++;
  30. }
  31. public:
  32. Foo() : id(num()), p(NULL) {
  33. std::cout << "cons()" << id << std::endl;
  34. p = new Bar;
  35. }
  36. Foo(const int val) : id(num()), p(NULL) {
  37. std::cout << "cons(int)" << id << ":" << val << std::endl;
  38. p = new Bar(val);
  39. }
  40. Foo(const Foo& f) : id(num()), p(NULL) {
  41. std::cout << "cons(Foo)" << id << ":" << f.id << std::endl;
  42. p = new Bar(*f.p);
  43. }
  44. ~Foo() {
  45. std::cout << "dest()" << id << std::endl;
  46. delete p;
  47. p = NULL;
  48. }
  49. Foo& operator = (const Foo& f) {
  50. std::cout << id << " = " << f.id << std::endl;
  51. p->val = f.p->val;
  52. return *this;
  53. }
  54. int getValue() const {
  55. if (p) return p->val;
  56. throw FooException(id);
  57. }
  58. int getId() const {
  59. return id;
  60. }
  61. };
  62.  
  63. Foo operator + (const Foo& f1, const Foo& f2) {
  64. std::cout << f1.getId() << " + " << f2.getId() << std::endl;
  65. Foo t(f1.getValue() + f2.getValue());
  66. return t;
  67. }
  68.  
  69. int main() {
  70. using namespace std;
  71. Foo f1, f2(123);
  72. Foo f3(f2), f4, f5;
  73.  
  74. f4 = f3;
  75.  
  76. f5 = f2 + f3 + f2;
  77.  
  78. try {
  79. cout << f1.getId() << " ... " << f1.getValue() << endl;
  80. cout << f2.getId() << " ... " << f2.getValue() << endl;
  81. cout << f3.getId() << " ... " << f3.getValue() << endl;
  82. cout << f4.getId() << " ... " << f4.getValue() << endl;
  83. cout << f5.getId() << " ... " << f5.getValue() << endl;
  84. } catch (FooException e) {
  85. cout << "fooerr" << e.getId() << endl;
  86. } catch (...) {
  87. cout << "err" << endl;
  88. }
  89.  
  90. return 0;
  91. }
Success #stdin #stdout 0s 3432KB
stdin
Standard input is empty
stdout
cons()0
cons(int)1:123
cons(Foo)2:1
cons()3
cons()4
3 = 2
1 + 2
cons(int)5:246
5 + 1
cons(int)6:369
4 = 6
dest()6
dest()5
0 ... 0
1 ... 123
2 ... 123
3 ... 123
4 ... 369
dest()4
dest()3
dest()2
dest()1
dest()0