Question

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)

Was it helpful?

Solution

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.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top