Advertisement
Guest User

Untitled

a guest
Apr 23rd, 2014
36
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.75 KB | None | 0 0
  1. class A {
  2.  
  3. public:
  4.  
  5. A();
  6.  
  7. A& operator=(const A& rhs)
  8. {
  9. b = rhs.b;
  10. return *this;
  11. }
  12.  
  13. private:
  14.  
  15. B b;
  16.  
  17. };
  18.  
  19. class A {
  20.  
  21. public:
  22.  
  23. A() : b(0)
  24. {
  25. b = new B;
  26. }
  27.  
  28. A& operator=(const A& rhs)
  29. {
  30. if (this != &rhs) {
  31. B* b1 = 0;
  32.  
  33. try {
  34. b1 = new B(*rhs.b);
  35. }
  36. catch {
  37. delete b1;
  38. throw;
  39. }
  40.  
  41. delete b;
  42. b = b1;
  43. }
  44. return *this;
  45. }
  46.  
  47. private:
  48.  
  49. B* b;
  50.  
  51. };
  52.  
  53. class A {
  54.  
  55. public:
  56.  
  57. A() : b(0)
  58. {
  59. b = new B;
  60. }
  61.  
  62. A& operator=(const A& rhs)
  63. {
  64. *b = *rhs.b;
  65. return *this;
  66. }
  67.  
  68. private:
  69.  
  70. B* b;
  71.  
  72. };
  73.  
  74. const B* A::GetB() const
  75. {
  76. return b;
  77. }
  78.  
  79. A a1, a2;
  80.  
  81. const B* my_b = a1.GetB();
  82.  
  83. a1 = a2; // this leaves my_b dangling!
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement