【问题标题】:Lazy initialization on static local data静态本地数据的延迟初始化
【发布时间】:2013-04-10 02:47:35
【问题描述】:

我有以下代码(为简单起见,省略了部分代码)

标题:

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 的线程安全不是我关心的问题)

【问题讨论】:

    标签: c++ static factory lazy-initialization


    【解决方案1】:

    按照标准,在函数范围内定义的静态成员的初始化只发生一次。

        static std::ostream os = createStream( *this ); // initialized only once
    

    此外,如果您使用 C++11,它也是线程安全的。

    请看看这些讨论:

    1) thread safety of local static initialization in C++11.

    2) Initialization of static variables.

    如果你没有使用 C++11,那么 operator() 不是线程安全的

     static std::ostream os = createStream( *this ); // if not C++11, this is not thread-safe and must be guarded.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多