Singleton with two getInstance() methods handing over a parent pointer?

坚强是说给别人听的谎言 提交于 2019-12-11 11:07:01

问题


I am still working on my Logger and I like the idea of a Singleton but my Logger derives frm QDialog, thus I would like to handle my Parent QWidget* MainWindow pointer when I call it first:

class Logger : public QDialog {
  Q_OBJECT

private:  
  explicit Logger(QWidget* parent = 0);

public:
  static Logger& firstInstance(QWidget* parent = 0) {
       static Logger theInstance(parent);
       return theInstance;
  }
  static Logger& instance() {
       return theInstance;
  }
  //..
}

So I would call Logger::firstInstance(this); from my MainWindow. And Logger::instance() from elsewhere. But my compiler mocks:

Error: 'theInstance' was not declared in this scope: return theInstance;

in the second instance() method.


回答1:


You should actually call just firstInstance from instance, since you have static variable in firstInstance it will be initialized only on first call, then just returned already initialized variable.

  static Logger& instance() {
       return firstInstance();
  }

But actually, function firstInstance in public interface is bad idea, probably it will be better to make it private and declare MainWindow friend class.



来源:https://stackoverflow.com/questions/32120691/singleton-with-two-getinstance-methods-handing-over-a-parent-pointer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!