FAQ 30.10 What if a class owns a referent and doesn t have all of the Big Three?

FAQ 30.10 What if a class owns a referent and doesn't have all of the Big Three?

Trouble is brewing.

The following EvilString class doesn't have an explicit copy constructor or assignment operator, so the compiler synthesizes a copy constructor and/or assignment operator when it sees an EvilString being copy initialized and/or assigned, respectively. Unfortunately the compiler-synthesized copy constructor and assignment operators copy only the pointer (shallow copy) rather than the referent (deep copy).

 #include <new> #include <cstring> #include <stdexcept> using namespace std; class EvilString { public:   EvilString(const char* s) throw(bad_alloc);  ~EvilString() throw();                                                      <-- 1                                                      <-- 2                                                      <-- 3 protected:   unsigned len_;     // ORDER DEPENDENCY; see FAQ 22.10   char* data_;       // ORDER DEPENDENCY; see FAQ 22.10 }; EvilString::EvilString(const char* s) throw(bad_alloc) : len_(strlen(s)) , data_(new char[len_ + 1]) { memcpy(data_, s, len_ + 1); } EvilString::~EvilString() throw() { delete[] data_; } 

(1) Since this contains remote ownership, it needs an explicit copy constructor

(2)

(3) Similar comments for the assignment operator

If an EvilString is copied (passed by value, for example; see FAQ 20.07), then the copy points to the same string data as the original. When the copy dies, the data they are sharing is deleted, leaving the original EvilString object with a dangling reference. Any use of the original object, including the implicit destruction when the original dies, will probably corrupt the heap, which will eventually crash the program.

 void sample(EvilString b) throw(bad_alloc) {   // Since EvilString lacks a proper copy constructor,   // changes to b's string data will also change a's string } int main() {   EvilString a = "xyzzy";   sample(a);   // Any use of a might corrupt the heap } 

Note that the problem is not with pass-by-value. The problem is that the copy constructor for class EvilString is broken. Similar comments can be made regarding the assignment operator.



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