Normally when I implement a singleton I make the instance dynamic and have a member function to delete it. In this case, I’m working on an embedded device and I’ve been told I can’t use dynamic memory. It valid for a class to have a static instance of itself within the class declaration, and return it by reference?
(Thread safety is not a concern here.)
class Foo {
private:
static Foo singleton;
Foo() { }
Foo(const Foo &rhs);
Foo &operator=(const Foo &rhs);
public:
inline static Foo &Instance(void) {
return singleton;
}
};
Foo Foo::singleton;
It is possible to have a static instance, but it is not desirable to have it at class level because it may then happen that it is not yet initialized on access (due to the not completely defined static initialization order). Instead you should use a function-local static:
That way it is guaranteed to get initialized the first time the
Instancefunction is called.