【问题标题】:Singleton with two getInstance() methods handing over a parent pointer?具有两个 getInstance() 方法的单例传递父指针?
【发布时间】:2015-11-14 05:45:32
【问题描述】:

我仍在处理我的Logger,我喜欢单例的想法,但我的 Logger 派生 frm QDialog,因此我想在我第一次调用它时处理我的 Parent QWidget* MainWindow 指针:

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

所以我会从我的主窗口调用Logger::firstInstance(this);。还有其他地方的 Logger::instance() 。但是我的编译器模拟了:

错误:“theInstance”未在此范围内声明: 返回实例;

在第二个instance() 方法中。

【问题讨论】:

  • 好吧,正如编译器所说:在您的第二种方法中没有名为 theInstance 的变量。那么编译器应该如何找到它呢?
  • 为什么记录器是一个对话框?对于记录器来说,这听起来很奇怪。
  • 考虑开始不喜欢 Singleton 的想法...
  • @PiotrNycz 当你无法证明你的论点时,它就是声音和烟雾
  • @molbdnilo 我在单独的对话框中显示输出

标签: c++ logging static singleton overloading


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-07
    • 1970-01-01
    • 1970-01-01
    • 2021-08-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多