FAQ 24.02 What is wrong with an object being assigned to itself?

Nothing, unless the programmer who developed the class failed to implement the assignment operator correctly.

Assigning an object to itself is called self-assignment.

No one intentionally assigns an object to itself (a = a). However, since two different pointers or references could refer to the same object (aliasing), a statement like a = b could assign an object to itself. If that happens, and if the object doesn't properly handle it, a disaster could occur, especially if remote ownership is involved (see FAQ 30.08). An example follows.

 #include <new> using namespace std; class Wilma { }; class Fred { public:   Fred()              throw(bad_alloc);   Fred(const Fred& f) throw(bad_alloc);  ~Fred()              throw();   Fred& operator= (const Fred& f) throw(bad_alloc);   //... private:   Wilma* p_; }; Fred::Fred()              throw(bad_alloc) : p_(new Wilma())      { } Fred::Fred(const Fred& f) throw(bad_alloc) : p_(new Wilma(*f.p_)) { } Fred::~Fred()             throw() { delete p_; } Fred& Fred::operator= (const Fred& f) throw(bad_alloc) {                                                      <-- 1   delete p_;                                         <-- 2   p_ = new Wilma(*f.p_);   return *this; } void sample(Fred& a, Fred& b) throw(bad_alloc) { a = b; } int main() {   Fred x;   sample(x, x); } 

(1) BAD FORM: Forgot to check for self-assignment!

(2) BAD FORM: Delete the old before allocating the new!

Even though the code of sample() doesn't appear to be assigning an object with itself, the two references a and b could (and in this case, do) refer to the same object. Unfortunately, the assignment operator fails to check for self-assignment, which means that the statement delete p_ deletes both this->p_ and f.p_. Yet the next line uses the deleted object *f.p_, meaning that the program is using a dangling reference. Depending on the contents of class Wilma, this could be a disaster.



C++ FAQs
C Programming FAQs: Frequently Asked Questions
ISBN: 0201845199
EAN: 2147483647
Year: 2005
Pages: 566
Authors: Steve Summit

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net