简体   繁体   中英

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

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

I really have no idea how static behaves when a function is called in this manner.

I would expect the function createStream would only be called once ( or never be called if operator() is never called

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)

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.

Pls have a look at these discussions:

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

2) Initialization of static variables .

If you are not using C++11 then operator() is not thread safe

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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