Advertisement
Guest User

Untitled

a guest
May 2nd, 2016
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.48 KB | None | 0 0
  1. #include <algorithm>
  2.  
  3. typedef int Data;
  4.  
  5. // Self assignment : Unsafe
  6. // Exception : Unsafe
  7. class Unsafe {
  8. Data *pData;
  9. public:
  10. Unsafe& operator=(const Unsafe& obj) {
  11. delete pData;
  12. pData = new Data(*obj.pData);
  13. return *this;
  14. }
  15. };
  16.  
  17. // Self assignment : Safe
  18. // Exception : Unsafe
  19. class Unsafe2 {
  20. Data *pData;
  21. public:
  22. Unsafe2& operator=(const Unsafe2& obj) {
  23. if (this == &obj)
  24. return *this;
  25. delete pData;
  26. pData = new Data(*obj.pData); // if exception occurs in new??
  27. return *this;
  28. }
  29. };
  30.  
  31. // Self assignment : Safe
  32. // Exception : Safe
  33. class Safe {
  34. Data *pData;
  35. public:
  36. Safe& operator=(const Safe& obj) {
  37. Data *pOrg = pData;
  38. pData = new Data(*obj.pData);
  39. delete pOrg;
  40. return *this;
  41. }
  42. };
  43.  
  44. // Self assignment : Safe
  45. // Exception : Unsafe
  46. class Unsafe3 {
  47. Data *pData, *pData2;
  48. public:
  49. Unsafe3& operator=(const Unsafe3& obj) {
  50. Data *pOrg = pData, *pOrg2 = pData2;
  51. pData = new Data(*obj.pData);
  52. pData2 = new Data(*obj.pData2); // if exception occurs in this new??
  53. delete pOrg;
  54. delete pOrg2;
  55. return *this;
  56. }
  57. };
  58.  
  59. // Using "copy and swap".
  60. // Self assignment : Safe
  61. // Exception : Safe
  62. class RealSafe {
  63. Data *pData, *pData2;
  64. public:
  65. void swap(RealSafe &obj) noexcept {
  66. std::swap(pData, obj.pData);
  67. std::swap(pData2, obj.pData2);
  68. }
  69. RealSafe& operator=(const RealSafe& obj) {
  70. RealSafe copy(obj);
  71. // std::swap(*this, copy); // BAD!! Infinite loop occurs!
  72. swap(copy);
  73. return *this;
  74. }
  75. };
  76.  
  77. int main() {
  78. RealSafe a, b;
  79. a = b = a = b = a = a = b = b;
  80. return 0;
  81. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement