Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

global static variable vs static variable in function?

Tags:

c++

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?

like image 383
Lucas Lima Avatar asked Aug 30 '12 00:08

Lucas Lima


2 Answers

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.

like image 51
Robᵩ Avatar answered Oct 29 '22 18:10

Robᵩ


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.

like image 24
snoopy Avatar answered Oct 29 '22 17:10

snoopy