2 Comments

  1. Instead of making the instance variable a pointer you can more easily return a function local static:

    class Singleton {
    public:
    static Singleton& GetInstance() {
    static Singleton instance;
    return instance;
    }

    private:
    Singleton();
    ~Singleton();
    };

    This way, the Singleton is also destroyed at the end of the program which is not the case with your implementation (a unique_ptr would help).

    The virtual destructor is not needed by the way, since you don’t derive from Singleton.

    In addition, I’d always return a reference here, since there will always be an object, i.e. you won’t get a nullptr, so there is no point for a pointer at all.

    • Hi Arne,

      Thanks for reading my post! I appreciate the feedback. I do like your suggestion to remove the pointer and return a reference to a local static instance. Especially if the instantiation is on a realtime critical path as it was avoid a dynamic allocation on heap. I do think that is a better solution than using a pointer but in the case where one was used, I agree using unique_ptr would improve the solution when the program exits.

      Not sure why I used a virtual destructor. It looks like my Eclipse configuration creates the class like that by default. Regardless, my mistake and thanks for pointing it out.

      Much respect,

      Bob

Comments are closed.