FAQ 16.16 What if the static object s destructor has important side effects that must eventually occur?

FAQ 16.16 What if the static object's destructor has important side effects that must eventually occur?

graphics/new_icon.gif

One limitation of the technique described in the previous FAQ is that it abandons the static Wilma object on the heap the Wilma object is never destructed. If the Wilma object's destructor has important side effects that should eventually happen, then the implementation of Fred::wilma() needs to be changed so that it simply returns a local static object by reference.

The following code shows how to apply this technique to the example from the previous FAQ. The local static pointer static Wilma* p = new Wilma(); has been changed to simply static Wilma w;, and the return statement simply returns the local static object w. Class Wilma is not shown since it is unchanged from the example in the previous FAQ.

 class Fred { public:   Fred() throw(); protected:   static Wilma& wilma() throw();                     <-- 1 }; inline Fred::Fred() throw() {   cout << "Fred ctor\n";   wilma().f();                                       <-- 2 } Fred x; Wilma& Fred::wilma() throw() {   static Wilma w;                                    <-- 3   return w; } 

(1) Same as in the previous FAQ

(2) Same as in the previous FAQ

(3) Used to be static Wilma* p = new Wilma();

Since the local static object w is static, it is initialized only the first time control flows over its declaration, that is, the first time Fred::wilma() is called. This is the same construct on first use semantics as was described in the previous FAQ, which is normally quite desirable.

Unfortunately, this solution has its own problems. Remember why this solution was proposed in the first place: the Wilma object's destructor has important side effects that need to eventually occur. Although this second solution guarantees that they will occur (assuming the Fred::wilma() function is called at least once), it introduces a new problem that the previous solution did not have: a static deinitialization order problem. In particular, if some static object's destructor calls Fred::wilma(), Murphy's Law says that that call will occur after the static Wilma object has been destructed. If that may occur, the best solution is the nifty counter technique, which is described in the next FAQ.



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