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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With