7

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?

3
  • With the global variable you risk naming conflicts. Commented Aug 30, 2012 at 0:44
  • See stackoverflow.com/questions/12186857/…. Commented Aug 30, 2012 at 0:54
  • @VoidStar: With the global function you risk naming conflicts. Commented Aug 30, 2012 at 6:59

2 Answers 2

10

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.

Sign up to request clarification or add additional context in comments.

1 Comment

While the intent is correct, with enough effort you can use the function static (in C++03) before initialization through recursive calls to the function.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.