组合静态成员和方法 [英] Combined static member and method
问题描述
考虑具有静态成员的类和静态方法来设置成员的值(以下内容基于@JamesKanze的示例):
class A_EXPORT InA
{
public:
static FILE * ourDest;
static void setDest(FILE& dest);
};
Dobbs博士中的文章(关于日志记录)建议将静态成员和静态方法组合如下:
//在头文件中
class A_EXPORT InA
{
public:
static FILE *& theDest(); //静态方法的静态成员太!
};
//在cpp文件中
FILE *& InA :: theDest()
{
static FILE * pStream = stderr;
return pStream;
}
//在用户文件中
InA :: theDest()= fopen(log.txt,a); // std :: ofstream(log.txt);问题:结合静态成员和静态方法的利弊是什么?
<
第二个版本的主要优点是避免了静态初始化顺序fiasco p>
如果 ourDest
有一个构造函数,那么不同的静态对象的构造函数可能会尝试使用<$ c $在之前,我们的 c> c> myDest
的构造函数已运行,导致未定义的行为。
但是如果静态对象被定义在一个函数里面,那么当这个定义被第一次击中时就被构造,所以在构造之前不可能访问它。
在你的case(类似于Dobbs博士案例),你的 theDest()
函数construct pStream
办法;这样做确保没有人使用 pStream
并且发现它为null。在第一种情况下,如果在调用 setDest
之前读取 outDest
,则可能为null。
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?
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.
这篇关于组合静态成员和方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!