TITLE: efficiency concerns and singleton access (Newsgroups: comp.lang.c++.moderated, 28 May 97) [ This is part of a discussion over initialization and access of globals. The code below shows a well-known example of a singleton idiom. The responder (Darrell) shows his tradeoff of access speed versus flexibility. -adc ] CLAMAGE: Steve Clamage > > > Instead, provide functional access: > > > extern T& MyObject(); > > > and define the function in some convenient translation unit: > > > T& MyObject() > > > { > > > static T t(args); > > > return t; > > > } DEROCCO: Paul D. DeRocco > This works, but can be inefficient, in that every reference to the > object involves a function call, plus a test of a hidden static boolean > flag to see if the constructor needs to be called. Plus those boolean > flags take up space. > From: Darrell K In cases where access speed is critical, I use a local static reference to the global object: void foo() { static T& ref = MyObject(); //... } This eliminates the function call on access but adds yet another boolean check. However, boolean checks are fast and don't really take much space. Plus, the check only occurs at the beginning of the function rather than each time the object is accessed from within the function. If the usage occurs many times in a class, I create a reference within the class: class Someclass { T& ref; public: Someclass(): ref(MyObject()) {} }; In this case, there is no boolean check once the class is instantiated. This is slightly less efficient than a global object since there is an extra indirection, but overall it works well.