简体   繁体   中英

Reference to a static, function local variable

Is the following code considered safe?

Foo& GetFoo()
{
    static std::once_flag fooInitFlag;
    static Foo f;

    std::call_once(fooInitFlag, [&Foo]()
    {
       Foo.Init();
    });

    return std::ref(f);

}

Instead of this posted code:

Foo& GetFoo()
{
    static std::once_flag fooInitFlag;
    static Foo f;

    std::call_once(fooInitFlag, [&Foo]()
    {
       Foo.Init();
    });

    return std::ref(f);
}

do this:

struct Initialized_foo
{
    Foo item;
    Initialized_foo() { item.Init(); }
};

auto get_foo()
    -> Foo&
{
    static Initialized_foo the_foo;
    return the_foo.item;
}

It's not more safe, but it's simpler, and hence more safe against inadvertently introduced bugs.

Note that the standard guarantees a single initialization here, even in the context of multi-threading.


Better, ideally each Foo insteance should be properly initialized by the Foo constructor, not by an Init method. But that's not always possible to arrange.

You asked:

Is the following code considered safe?

The answer is yes.

Another implementation:

// Not exposed to the outside.
static Foo& getInitializedFoo();
{
    static Foo f;
    f.Init();
    return f;
}

Foo& GetFoo()
{
    static Foo& f = getInitializedFoo();
    return f;
}

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