⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 mi10.htm

📁 一个非常适合初学者入门的有关c++的文档
💻 HTM
📖 第 1 页 / 共 2 页
字号:
 More Effective C++ | Item 10: Prevent resource leaks in constructors Back to Item 9: Use destructors to prevent resource leaksContinue to Item 11: Prevent exceptions from leaving destructorsItem 10: Prevent resource leaks in constructors.Imagine you're developing software for a multimedia address book. Such an address book might hold, in addition to the usual textual information of a person's name, address, and phone numbers, a picture of the person and the sound of their voice (possibly giving the proper pronunciation of their name).To implement the book, you might come up with a design like this: class Image {                        // for image datapublic:  Image(const string& imageDataFileName);  ...};class AudioClip {                    // for audio datapublic:  AudioClip(const string& audioDataFileName);  ...};class PhoneNumber {         ... };   // for holding phone numbersclass BookEntry {                    // for each entry in thepublic:                              // address bookBookEntry(const string& name,          const string& address = "",          const string& imageFileName = "",          const string& audioClipFileName = "");~BookEntry();// phone numbers are added via this functionvoid addPhoneNumber(const PhoneNumber& number);...private:  string theName;                 // person's name  string theAddress;              // their address  list<PhoneNumber> thePhones;    // their phone numbers  Image *theImage;                // their image  AudioClip *theAudioClip;        // an audio clip from them};Each BookEntry must have name data, so you require that as a constructor argument (see Item 3), but the other fields the person's address and the names of files containing image and audio data are optional. Note the use of the list class to hold the person's phone numbers. This is one of several container classes that are part of the standard C++ library (see Item E49 and Item 35).A straightforward way to write the BookEntry constructor and destructor is as follows: BookEntry::BookEntry(const string& name,                     const string& address,                     const string& imageFileName,                     Const string& audioClipFileName): theName(name), theAddress(address),  theImage(0), theAudioClip(0){  if (imageFileName != "") {    theImage = new Image(imageFileName);  }if (audioClipFileName != "") {theAudioClip = new AudioClip(audioClipFileName);  }}BookEntry::~BookEntry(){  delete theImage;  delete theAudioClip;}The constructor initializes the pointers theImage and theAudioClip to null, then makes them point to real objects if the corresponding arguments are non-empty strings. The destructor deletes both pointers, thus ensuring that a BookEntry object doesn't give rise to a resource leak. Because C++ guarantees it's safe to delete null pointers, BookEntry's destructor need not check to see if the pointers actually point to something before deleting them.Everything looks fine here, and under normal conditions everything is fine, but under abnormal conditions under exceptional conditions things are not fine at all.Consider what will happen if an exception is thrown during execution of this part of the BookEntry constructor: if (audioClipFileName != "") {  theAudioClip = new AudioClip(audioClipFileName);}An exception might arise because operator new (see Item 8) is unable to allocate enough memory for an AudioClip object. One might also arise because the AudioClip constructor itself throws an exception. Regardless of the cause of the exception, if one is thrown within the BookEntry constructor, it will be propagated to the site where the BookEntry object is being created.Now, if an exception is thrown during creation of the object theAudioClip is supposed to point to (thus transferring control out of the BookEntry constructor), who deletes the object that theImage already points to? The obvious answer is that BookEntry's destructor does, but the obvious answer is wrong. BookEntry's destructor will never be called. Never. C++ destroys only fully constructed objects, and an object isn't fully constructed until its constructor has run to completion. So if a BookEntry object b is created as a local object, void testBookEntryClass(){  BookEntry b("Addison-Wesley Publishing Company",              "One Jacob Way, Reading, MA 01867");...}and an exception is thrown during construction of b, b's destructor will not be called. Furthermore, if you try to take matters into your own hands by allocating b on the heap and then calling delete if an exception is thrown, void testBookEntryClass(){  BookEntry *pb = 0;  try {    pb = new BookEntry("Addison-Wesley Publishing Company",                       "One Jacob Way, Reading, MA 01867");    ...  }  catch (...) {                // catch all exceptions     delete pb;                // delete pb when an                               // exception is thrown     throw;                    // propagate exception to  }                            // caller  delete pb;                   // delete pb normally}you'll find that the Image object allocated inside BookEntry's constructor is still lost, because no assignment is made to pb unless the new operation succeeds. If BookEntry's constructor throws an exception, pb will be the null pointer, so deleting it in the catch block does nothing except make you feel better about yourself. Using the smart pointer class auto_ptr<BookEntry> (see Item 9) instead of a raw BookEntry* won't do you any good either, because the assignment to pb still won't be made unless the new operation succeeds.There is a reason why C++ refuses to call destructors for objects that haven't been fully constructed, and it's not simply to make your life more difficult. It's because it would, in many cases, be a nonsensical thing possibly a harmful thing to do. If a destructor were invoked on an object that wasn't fully constructed, how would the destructor know what to do? The only way it could know would be if bits had been added to each object indicating how much of the constructor had been executed. Then the destructor could check the bits and (maybe) figure out what actions to take. Such bookkeeping would slow down constructors, and it would make each object larger, too. C++ avoids this overhead, but the price you pay is that partially constructed objects aren't automatically destroyed. (For an example of a similar trade-off involving efficiency and program behavior, turn to Item E13.)Because C++ won't clean up after objects that throw exceptions during construction, you must design your constructors so that they clean up after themselves. Often, this involves simply catching all possible exceptions, executing some cleanup code, then rethrowing the exception so it continues to propagate. This strategy can be incorporated into the BookEntry constructor like this: BookEntry::BookEntry(const string& name,          	     const string& address,          	     const string& imageFileName,	      	     const string& audioClipFileName): theName(name), theAddress(address),  theImage(0), theAudioClip(0){  try {                            // this try block is new    if (imageFileName != "") {      theImage = new Image(imageFileName);    }  if (audioClipFileName != "") {      theAudioClip = new AudioClip(audioClipFileName);    }  }  catch (...) {                      // catch any exception    delete theImage;                 // perform necessary    delete theAudioClip;             // cleanup actions    throw;                           // propagate the exception  }}There is no need to worry about BookEntry's non-pointer data members. Data members are automatically initialized before a class's constructor is called, so if a BookEntry constructor body begins executing, the object's theName, theAddress, and thePhones data members have already been fully constructed. As fully constructed objects, these data members will be automatically destroyed when the BookEntry object containing them is, and there is no need for you to intervene. Of course, if these objects' constructors call functions that might throw exceptions, those constructors have to worry about catching the exceptions and performing any necessary cleanup before allowing them to propagate.You may have noticed that the statements in BookEntry's catch block are almost the same as those in BookEntry's destructor. Code duplication here is no more tolerable than it is anywhere else, so the best way to structure things is to move the common code into a private helper function and have both the constructor and the destructor call it: class BookEntry {public:  ...                      // as beforeprivate:  ...  void cleanup();          // common cleanup statements

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -