Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Global instance of a class in C++

Tags:

c++

singleton

As the title says. How would I create an instance of a class that is globally available(for example I have a functor for printing and i want to have a single global instance of this(though the possibility of creating more)).

like image 821
Alex Gaynor Avatar asked Nov 18 '08 04:11

Alex Gaynor


3 Answers

Going to all the effort of making a singleton object using the usual pattern isn't addressing the second part of your question - the ability to make more if needed. The singleton "pattern" is very restrictive and isn't anything more than a global variable by another name.

// myclass.h

class MyClass {
public:
    MyClass();
    void foo();
    // ...
};

extern MyClass g_MyClassInstance;

// myclass.cpp

MyClass g_MyClassInstance;

MyClass::MyClass()
{
    // ...
}

Now, in any other module just include myclass.h and use g_MyClassInstance as usual. If you need to make more, there is a constructor ready for you to call.

like image 56
Greg Hewgill Avatar answered Sep 17 '22 23:09

Greg Hewgill


First off the fact that you want global variables is a 'code smell' (as Per Martin Fowler).

But to achieve the affect you want you can use a variation of the Singleton.
Use static function variables. This means that variable is not created until used (this gives you lazy evaluation) and all the variables will be destroyed in the reverse order of creation (so this guarantees the destructor will be used).

class MyVar
{
    public:
        static MyVar& getGlobal1()
        {
            static MyVar  global1;
            return global1;
        }
        static MyVar& getGlobal2()
        {
            static MyVar  global2;
            return global2;
        }
        // .. etc
}
like image 26
Martin York Avatar answered Sep 21 '22 23:09

Martin York


As a slight modification to the singleton pattern, if you do want to also allow for the possibility of creating more instances with different lifetimes, just make the ctors, dtor, and operator= public. That way you get the single global instance via GetInstance, but you can also declare other variables on the heap or the stack of the same type.

The basic idea is the singleton pattern, however.

like image 43
Mike Kale Avatar answered Sep 20 '22 23:09

Mike Kale