0

I am implementing the singleton pattern in C++ with the following implementation.

class Singleton
{
public:
    ~Singleton() { // some cleaning up implementation }

    // Delete copy constructor and copy assignment.
    Singleton(const Singleton& other) = delete;
    Singleton& operator=(const Singleton& other) = delete;

    static Singleton& GetInstance() { return s; }

private:
    static Singleton s;

    Singleton() { // some initialization implementation }
};

and I want to know if this is functionally different from a class that does not have a static member, but rather a static function which has a static variable in its own scope like this.

class Singleton
{
public:
    ~Singleton() { // some cleaning up implementation }

    // Delete copy constructor and copy assignment.
    Singleton(const Singleton& other) = delete;
    Singleton& operator=(const Singleton& other) = delete;

    static Singleton& GetInstance() 
    {
        static Singleton s;
        return s;
    }

private:
    Singleton() { // some initialization implementation }
};

As a follow up, does the GetInstance function need to return a reference Singleton&? Will the function attempt to copy construct the static variable into the return value, if the return is not a reference?

nick2225
  • 413
  • 3
  • 12
  • 2
    When these two object get initialized is very different, and it can have a huge impact on correctness. Look up Meyers' Singleton for a design pattern that relies on this difference. – François Andrieux Oct 19 '21 at 18:37
  • Looks like my question was a duplicate, I just learned about some of the issues when using a static member variable as described here: https://isocpp.org/wiki/faq/ctors#static-init-order. – nick2225 Oct 19 '21 at 18:39

0 Answers0