Consider alternatives to temporary objects

Constructors, like any function, take time to execute. If you use an object as a constant, it's better to create it once and use it repeatedly. One way to do this is to make the object static. By placing it at file scope, it is implicitly static, or if only used by one function, it can be static inside the function. Unless the class in question relies implicitly on other static objects, this latter technique has the advantage of not falling prey to the dreaded order of static constructors problem described in "Static object constructors" on page 74. Unfortunately, it has concurrency implications, whereas an object at file scope does not. So,
for example:

    
    
Foo(TToken("Hi Mom")); // Pay for constructor each time, but safe.

      
    
      TToken hiMom("Hi Mom");             // No concurrency issues, but always
      void Bar()                          //  constructed even if never used.
      {
          Foo(hiMom);
      }
      
    
      void Bar()
      {
          static TToken hiMom("Hi Mom");  // NOTE: Potential concurrency problems!
      
          Foo(hiMom);
      }

[Contents] [Previous] [Next]
Click the icon to mail questions or corrections about this material to Taligent personnel.
Copyright©1995 Taligent,Inc. All rights reserved.

Generated with WebMaker