0

I have example code on C++ that describes my solution:

#include <iostream>

class Singleton {
private:
    static Singleton* instance;
    Singleton() {
        std::cout << "Instance created" << std::endl;
    }
    Singleton(const Singleton&);
    Singleton& operator=(Singleton&);
public:
    static Singleton* getInstance();
    static void m1();
    void m2();
};

Singleton* Singleton::instance = 0;

Singleton* Singleton::getInstance() {
  if (!instance) {
        instance = new Singleton();
    }
    return instance;
}

void Singleton::m1() {
    std::cout << "Called m1" << std::endl;
    instance->m2();
}

void Singleton::m2() {
  std::cout << "Called m2" << std::endl;
}

int main() {
    Singleton* singleton = Singleton::getInstance();
    Singleton::m1();
    return 1;
}

Is it correct that I call instance method m2 from static method m1? Doesn't this cause any problems in maintaining and understanding the code, or would it be better to make m2 method also static?

  • 1
    [Retiring the Singleton Pattern: Concrete Suggestions for What to use Instead - Peter Muldoon](https://www.youtube.com/watch?v=K5c7uvWe_hw) – JHBonarius Dec 22 '20 at 13:59
  • 2
    Well, if `m1` gets called before `getInstance()`, you'll have obvious problems. – Sam Varshavchik Dec 22 '20 at 14:06
  • Yes, `m1` should do `getInstance()->m2();`.- Your singleton isn't thread safe though. Two threads could create an instance at the same time. If you're going to use a singleton, it's often easier to go with a `static Singleton instance;` and return a reference to that. – Ted Lyngmo Dec 22 '20 at 14:22
  • That is, if I replace ```instance->m2()``` with ```getInstance()->m2()``` and make Meyer's Singleton instead of mine - it will be correct code, @TedLyngmo? – Yehor Bublyk Dec 22 '20 at 14:34
  • @YehorBublyk It'll be safer anyway. I didn't read everything through to find other potential problems. – Ted Lyngmo Dec 22 '20 at 14:36

0 Answers0