Hi,

Can some one please explain the function FredPtr& operator= (const FredPtr& p) int the following lines of code ?

Qt Code:
  1. class FredPtr;
  2.  
  3. class Fred {
  4. public:
  5. Fred() : count_(0) /*...*/ { } // All ctors set count_ to 0 !
  6. ...
  7. private:
  8. friend class FredPtr; // A friend class
  9. unsigned count_;
  10. // count_ must be initialized to 0 by all constructors
  11. // count_ is the number of FredPtr objects that point at this
  12. };
  13.  
  14. class FredPtr {
  15. public:
  16. Fred* operator-> () { return p_; }
  17. Fred& operator* () { return *p_; }
  18. FredPtr(Fred* p) : p_(p) { ++p_->count_; } // p must not be NULL
  19. ~FredPtr() { if (--p_->count_ == 0) delete p_; }
  20. FredPtr(const FredPtr& p) : p_(p.p_) { ++p_->count_; }
  21. FredPtr& operator= (const FredPtr& p)
  22. { // DO NOT CHANGE THE ORDER OF THESE STATEMENTS!
  23. // (This order properly handles self-assignment)
  24. // (This order also properly handles recursion, e.g., if a Fred contains FredPtrs)
  25. Fred* const old = p_;//const pointer to a const Fred
  26. p_ = p.p_;
  27. ++p_->count_;
  28.  
  29. //Will -- operator not change the count ? But Fred is const ???
  30. if (--old->count_ == 0) delete old;
  31. return *this;
  32. }
  33. private:
  34. Fred* p_; // p_ is never NULL
  35. };
To copy to clipboard, switch view to plain text mode 

Thanks a lot.