FAQ 16.18 What are some criteria for choosing between all these various techniques?

graphics/new_icon.gif

Here are the pros and cons of each of the four techniques that were presented.

  • Construct on first use with new: Users access the static object via a non-inline access function. The access function has a local static pointer and allocates the object via new. Pro: The technique is easy to remember, simple to use, efficient during startup, safe during startup, and safe during shutdown. Con: The static object is abandoned on the heap if the static object's destructor has important side effects that must occur, this technique cannot be used. (See FAQ 16.15.)

  • Construct on first use with a local static object: Users access the static object via a non-inline access function. The access function has a local static object. Pro: The technique is easy to remember, simple to use, efficient during startup, and safe during startup, and it eventually destructs the object. Con: The technique is not safe during shutdown if a static object's destructor calls the access function, the static object could be accessed after it is destroyed, which would be a disaster. (See FAQ 16.16.)

  • Construct before first use with a class-scope static object: Users access the static object via a non-inline access function. The access function is not inline and is defined in the same file that defines the static object. Pro: The technique is easy to remember, simple to use, efficient during startup, and safe during startup, and it eventually destructs the object. Con 1: The technique is not safe during shutdown if a static object's destructor calls the access function, the static object could be accessed after it is destroyed, which would be a disaster. Con 2: the technique doesn't enforce the constraint that the object be accessed only via the access function. (See FAQ 16.16.)

  • Nifty counter: The static object is constructed when the nifty counter is incremented from 0 and is destructed when the nifty counter is decremented to 0. Pro: The technique is simple to use, safe during startup, and safe during shutdown, and it eventually destructs the object. Con: Potential performance problem during startup and shutdown. (See FAQ 16.17.)

In our experience, a significant percentage of static objects that should be constructed before they are first used are registry objects (for example, a map object that will be populated during static initialization by other static objects). In most of these cases, the first technique is sufficient since the map object rarely has to be destructed it can be abandoned on the heap. This is good news because the first technique is easy to use, easy to remember, is fast, and is safe during both startup and shutdown.



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