简体   繁体   English

静态本地数据的延迟初始化

[英]Lazy initialization on static local data

I have the following code (part of it was omitted for simplicity) 我有以下代码(为简单起见,省略了一部分)

header: 标题:

class DbgModuleMarker
{
public:
    DbgModuleMarker( std::string name );

    static std::ostream createStream( const DbgModuleMarker& marker );

    std::ostream& operator()() const;

};

extern DbgModuleMarker PHYSICS;

source: 资源:

std::ostream& DbgModuleMarker::operator()() const
{
    static std::ostream os = createStream( *this );
    return os;
}

the goal of this code is to allow operator() to be used as follows 该代码的目的是允许将operator()如下使用

debug_modules::PHYSICS() << "Foo" << endl;

I really have no idea how static behaves when a function is called in this manner. 我真的不知道以这种方式调用函数时static的行为。

I would expect the function createStream would only be called once ( or never be called if operator() is never called 我希望函数createStream只会被调用一次(或者如果从不调用operator()则永远不会被调用

I would like to know if the behavior i'm expecting is what will happen and if this is a could idea or i'm doing something very wrong without noticing it. 我想知道我期望的行为是否会发生,这是否可行,或者我在做错了什么而没有注意到它。

What are the impacts on thread safety and exception safety? 对线程安全和异常安全有什么影响?

(consider the stream created would itself be thread-safe because the thread safety of std::ostream is not my concern here) (考虑到创建的流本身就是线程安全的,因为在这里我不关心std :: ostream的线程安全性)

As per standard, initialization of static members defined within function scope happens only once. 按照标准,在函数范围内定义的静态成员的初始化仅发生一次。

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

Also, it is thread-safe if you are using C++11. 另外,如果您使用的是C ++ 11,它是线程安全的。

Pls have a look at these discussions: 请看一下这些讨论:

1) thread safety of local static initialization in C++11 . 1) C ++ 11中局部静态初始化的线程安全性

2) Initialization of static variables . 2) 静态变量的初始化

If you are not using C++11 then operator() is not thread safe 如果您未使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM