FAQ 30.07 Which of the Big Three usually shows up first?

An explicit destructor.

Developers typically discover the need to do something special during a normal constructor, which frequently necessitates undoing the special action in the destructor. In almost all cases, the class needs a copy constructor so that the special thing will be done during copying, and the class also needs an assignment operator so that the special thing will be done during assignment.

The destructor is the signal for applying the Law. Pretend that the keyboard's ~ (tilde) key is painted bright red and is wired up to a siren.

In the following example, the constructor of class MyString allocates memory, so its destructor deletes the memory. Typing the ~ of ~MyString() should sound a siren for the Law of the Big Three.

 #include <new> #include <cstring> using namespace std; class MyString { public:   MyString(const char* s) throw(bad_alloc);  ~MyString() throw();   MyString(const MyString& s) throw();   MyString& operator= (const MyString& s) throw(); protected:   unsigned len_;     // ORDER DEPENDENCY; see FAQ 22.10   char*    data_;    // ORDER DEPENDENCY; see FAQ 22.10 }; MyString::MyString(const char* s) throw(bad_alloc) : len_(strlen(s)) , data_(new char[len_ + 1]) { memcpy(data_, s, len_ + 1); } MyString::~MyString() throw() { delete[] data_; } int main() { MyString s = "xyzzy"; } 

Classes that own allocated memory (hash tables, linked lists, and so forth) generally need the Big Three (see FAQ 30.08).



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