简体   繁体   中英

global static variable vs static variable in function?

What's the diference between use:

static Foo foo;
// ...
foo.func();

And:

Foo& GetFoo(void) 
{
    static Foo foo;
    return foo;
}

// ...

GetFoo().func();

Which is better?

The principal difference is when construction occurs. In the first case, it occurs sometime before main() begins. In the second case, it occurs during the first call to GetFoo() .

It is possible, in the first case, for code to (illegally) use foo prior to its initialization. That is not possible in the second case.

A GetFoo is generally used when you don't want copies of your class/object. For example:

class Foo
{
private:
    Foo(){};
    ~Foo();
public:
    static Foo* GetFoo(void) 
    {
        static Foo foo;
        return &foo;
    }

    int singleobject;
};

You can externally access singleobject via Foo::GetFoo()->sinlgeobject . The private constructors and destructors avoid your class getting copies created.

For the use of static Foo foo , you must have public constructors declared which means you are always accessing your class by it, but your class will also be able to get copies.

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