2

Consider a class with a static member and a static method to set the value of the member (following is based on @JamesKanze 's example ):

class A_EXPORT InA
{
    public:
     static FILE* ourDest;
     static void setDest( FILE& dest );
};

An article (on logging) in Dr. Dobbs would suggest that the static member and static method be combined as follows:

// in header file
class A_EXPORT InA
{
    public:
     static FILE*& theDest();  // a static member that is a static method too!
};

// in cpp file
FILE*& InA::theDest()
{
    static FILE* pStream = stderr;
    return pStream;
}

// in user's file
InA::theDest()  =  fopen("log.txt","a"); //std::ofstream( "log.txt" );

Question: What are the pros and cons of combining a static member and a static method?

Community
  • 1
  • 1
user1823664
  • 1,071
  • 9
  • 16
  • @MattMcNabb @quantdev **Is this correct?:** A static class member that is _not_ also a static method (a) requires the static member to be declared in a cpp file and, when building and using libraries on Windows, (b) requires the use of `__declspec( [dllexport, dllimport] )`; in contrast, the use of a static member that is also a static method eliminates these two requirements. – user1823664 Jun 14 '14 at 22:19

2 Answers2

2

The main advantage of the second version is to avoid the static initialization order fiasco.

If ourDest had a constructor, then it is possible that a different static object's constructor might try to use ourDest before ourDest's constructor had run, causing undefined behaviour.

But if the static object is defined inside a function, then it is constructed when that definition is first hit, so there is no possibility of accessing it before construction.

In your case (which is like the Dr. Dobbs case), your theDest() function "constructs" pStream in a similar way; doing this ensures that nobody ever uses pStream and finds it to be null. In your first case, outDest might be null if it is read before setDest has been called.

M.M
  • 138,810
  • 21
  • 208
  • 365
2

This pattern is often called the Meyer's singleton, an implementation of the Singleton design pattern.

The main advantage is its ability to deal with the static initialization order fiasco, which is basically the inability to predict in which order static objects are initialized across translation units.

Community
  • 1
  • 1
quantdev
  • 23,517
  • 5
  • 55
  • 88