本文介绍了具有两个getInstance()方法的单例移交父指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我仍在使用记录器 a>并且我喜欢Singleton的想法,但是我的Logger派生了frm QDialog,因此我想在第一次调用它时处理我的Parent QWidget * MainWindow指针:

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;
  }
  //..
}

因此,我将从MainWindow调用Logger::firstInstance(this);.还有Logger :: instance()从其他地方来.但是我的编译器模拟了:

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

在第二个instance()方法中.

推荐答案

您实际上应该只从instance调用firstInstance,因为您在firstInstance中具有静态变量,它将仅在第一次调用时进行初始化,然后返回已经初始化的变量.

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();
  }

但是实际上,公共接口中的函数firstInstance是个坏主意,可能最好将它设为私有并声明MainWindow朋友类.

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

这篇关于具有两个getInstance()方法的单例移交父指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!