FAQ 31.05 Should an object manage two or more resources?

graphics/new_icon.gif

Not usually.

An object that manages a resource should manage exactly one resource. Use composition to combine multiple "pure" resource manager objects (for example, multiple auto_ptr<T> objects, File objects, and so forth). This guideline is a corollary of the guideline presented in the previous FAQ.

If an object manages two or more resources, the first resource may leak if the second allocation throws an exception. In particular, when an exception occurs during the execution of a constructor, the object's destructor is not executed so the destructor won't release the resource that was successfully allocated. In the following example, class Fred manages two resources; an X allocation and a Y allocation. When Fred's constructor throws an exception as a result of allocating a Y, the X resource leaks.

 #include <new> #include <iostream> using namespace std; class X { }; class Y { public:   Y() throw(int); }; Y::Y() throw(int)   { throw 42; } class Fred { public:   Fred() throw(bad_alloc, int);  ~Fred() throw(); protected:   X* x_;   Y* y_; }; Fred::Fred() throw(bad_alloc, int)   : x_(new X())   , y_(new Y())   { } Fred::~Fred() throw()   { cout << "Not reached #1\n"; delete y_; delete x_; } int main() {   try {     Fred f;     cout << "Not reached #2\n";   }   catch (int e) {     cout << "Exception caught: " << e << "\n";   } } 

Because the guideline is violated, the X object leaks: the delete x_ instruction is never executed. Either Fred should focus on being a manager of a resource not two or more resources or Fred should delegate the resource management responsibility to some other class. In other words, either get rid of the Y resource from Fred or change the X* to an auto_ptr<X>.

In those cases where it is not possible to abide by the discipline, a try block can be put in the constructor initialization list. Use this only as a last resort.



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