0

I am reading someone else's code. It consists of:

class foo 
{
public:
    /*
     * Other functions
     */


    void BeginSession() { /* some code */ }

    void EndSession() { /* some code */ }

    static foo& Get()
    {
        static foo instance;
        return instance;
    }
};

int main()
{
    foo::Get().BeginSession();

    function_a();

    foo::Get().EndSession();
}

What is the purpose of the following piece of code? Because it seems to me that it creates an instance of foo and then makes it usable inside function_a().

static foo& Get()
{
    static foo instance;
    return instance;
}

Thank you in advance for taking the time to answer this. I know my title is a bit silly, but if you could rephrase it better, please be my guest.

debruss
  • 149
  • 8
  • 1
    It's basically the singleton pattern without preventing other instances of `foo` from being created... – fabian Apr 02 '21 at 07:50
  • 1
    That is how the singleton pattern is implemented in C++11. You can read more about this here https://www.modernescpp.com/index.php/thread-safe-initialization-of-a-singleton. – Marius Bancila Apr 02 '21 at 07:53
  • 1
    It's a singleton class, meaning that you are only ever supposed to have one instance of it. Read the dupe question or [this Wikipedia article](https://en.wikipedia.org/wiki/Singleton_pattern). – einpoklum Apr 02 '21 at 07:53
  • @fabian Thanks for answering. I'm sorry for the dupe, but I did not now that it was called and I couldn't find it by googling. – debruss Apr 02 '21 at 07:55

0 Answers0