Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <algorithm>
- typedef int Data;
- // Self assignment : Unsafe
- // Exception : Unsafe
- class Unsafe {
- Data *pData;
- public:
- Unsafe& operator=(const Unsafe& obj) {
- delete pData;
- pData = new Data(*obj.pData);
- return *this;
- }
- };
- // Self assignment : Safe
- // Exception : Unsafe
- class Unsafe2 {
- Data *pData;
- public:
- Unsafe2& operator=(const Unsafe2& obj) {
- if (this == &obj)
- return *this;
- delete pData;
- pData = new Data(*obj.pData); // if exception occurs in new??
- return *this;
- }
- };
- // Self assignment : Safe
- // Exception : Safe
- class Safe {
- Data *pData;
- public:
- Safe& operator=(const Safe& obj) {
- Data *pOrg = pData;
- pData = new Data(*obj.pData);
- delete pOrg;
- return *this;
- }
- };
- // Self assignment : Safe
- // Exception : Unsafe
- class Unsafe3 {
- Data *pData, *pData2;
- public:
- Unsafe3& operator=(const Unsafe3& obj) {
- Data *pOrg = pData, *pOrg2 = pData2;
- pData = new Data(*obj.pData);
- pData2 = new Data(*obj.pData2); // if exception occurs in this new??
- delete pOrg;
- delete pOrg2;
- return *this;
- }
- };
- // Using "copy and swap".
- // Self assignment : Safe
- // Exception : Safe
- class RealSafe {
- Data *pData, *pData2;
- public:
- void swap(RealSafe &obj) noexcept {
- std::swap(pData, obj.pData);
- std::swap(pData2, obj.pData2);
- }
- RealSafe& operator=(const RealSafe& obj) {
- RealSafe copy(obj);
- // std::swap(*this, copy); // BAD!! Infinite loop occurs!
- swap(copy);
- return *this;
- }
- };
- int main() {
- RealSafe a, b;
- a = b = a = b = a = a = b = b;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement