c++ - 具有两个 getInstance() 方法的单例移交父指针?

标签 c++ logging static singleton overloading

我仍在研究我的 Logger我喜欢 Singleton 的想法,但我的 Logger 派生自 rm 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() 。但是我的编译器模拟了:

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

在第二个 instance() 方法中。

最佳答案

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

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

但实际上,公共(public)接口(interface)中的函数 firstInstance 不是一个好主意,可能将其设为私有(private)并声明 MainWindow 友元类会更好。

关于c++ - 具有两个 getInstance() 方法的单例移交父指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32120691/

相关文章:

c++ - 如何以线程安全的方式在 openmp 中实现每个进程一次写入全局共享变量?

linux - rsyslog 发送 IP 地址而不是主机名

logging - 应用日志聚合、管理和通知

c - 关于C9 9's array size "保证”功能参数中的特性的实际优势?

android - NV21 ByteArray 到 array2d<rgb_pixel>

c++ - 如何防止阻塞路径?

c++ - 如何从成员函数中设置类静态数据成员的值?

java - 在 Java Web 应用程序中使用静态方法和变量

c++ - 未定义行为 : value of array element changes implicitly/illogically

java - 并发日志记录到 sql DB - 线程不并行运行