[英]Lazy initialization on static local data
我有以下代码(为简单起见,省略了一部分)
标题:
class DbgModuleMarker
{
public:
DbgModuleMarker( std::string name );
static std::ostream createStream( const DbgModuleMarker& marker );
std::ostream& operator()() const;
};
extern DbgModuleMarker PHYSICS;
资源:
std::ostream& DbgModuleMarker::operator()() const
{
static std::ostream os = createStream( *this );
return os;
}
该代码的目的是允许将operator()
如下使用
debug_modules::PHYSICS() << "Foo" << endl;
我真的不知道以这种方式调用函数时static的行为。
我希望函数createStream
只会被调用一次(或者如果从不调用operator()
则永远不会被调用
我想知道我期望的行为是否会发生,这是否可行,或者我在做错了什么而没有注意到它。
对线程安全和异常安全有什么影响?
(考虑到创建的流本身就是线程安全的,因为在这里我不关心std :: ostream的线程安全性)
按照标准,在函数范围内定义的静态成员的初始化仅发生一次。
static std::ostream os = createStream( *this ); // initialized only once
另外,如果您使用的是C ++ 11,它是线程安全的。
请看一下这些讨论:
2) 静态变量的初始化 。
如果您未使用C ++ 11,则operator()不是线程安全的
static std::ostream os = createStream( *this ); // if not C++11, this is not thread-safe and must be guarded.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.