c++ - 对单例模式的这方面感到困惑

标签 c++ design-patterns singleton

我根据在网上找到的教程改编了我的 Singleton 类。我的标题看起来像这样:

class Logger{
public:
    static Logger *instance();
    ~Logger();
private:
    Logger();
    static Logger *instance_;
};

cpp 文件是:

Logger* Logger::instance_=nullptr;  //Confused about this 

Logger *Logger::instance(){
    if (instance_==nullptr){
        instance_=new Logger();
    }
    return instance_;
}

Logger::Logger(){}

几个问题:

1) 在我的 cpp 的第一行中,如果我只写“Logger::instance_=nullptr;”然后我得到一个错误。既然已经在头文件中声明了,为什么我还需要再次提到instance_是一个指针呢?

2) 为什么我不能将头文件本身中的instance_初始化为“static Logger *instance_=nullptr;”?这样做会出现以下错误:

error: ‘constexpr’ needed for in-class initialization of static data member ‘Logger* Logger::instance_’ of non-integral type [-fpermissive] static Logger*instance_=nullptr; ^

谢谢!

最佳答案

Question 1) In the first line of my cpp, if I write just Logger::instance_=nullptr; then I get an error. Since it's already been declared in the header, why do I need to mention that instance_ is a pointer again?

来自 C++ 标准草案 N3337:

9.4.2 Static data members

5 static data members of a class in namespace scope have external linkage (3.5).

这类似于声明

extern int a;

在 .h 文件中并定义

int a = 10;

在 .cpp 文件中。定义时,您必须指定 a 的类型。

Question 2) Why can't I initialize instance_ in the header file itself as "static Logger *instance_=nullptr;"?

来自 C++ 标准草案 N3337(强调我的):

9.4.2 Static data members

2 The declaration of a static data member in its class definition is not a definition and may be of an incomplete type other than cv-qualified void. The definition for a static data member shall appear in a namespace scope enclosing the member’s class definition. In the definition at namespace scope, the name of the static data member shall be qualified by its class name using the :: operator.

更新,回应OP的评论

假设你有:

namespace detail
{
   class Foo
   {
       static int var;
   };
}

Foo::var 必须在 Foo 的封闭命名空间中定义。

namespace detail
{
   int Foo:var = 0;
}

在类没有显式封闭命名空间的情况下,全局范围是它的封闭命名空间。

关于c++ - 对单例模式的这方面感到困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26923781/

相关文章:

safari - 为什么 Safari 会翻转我的 SVG 背景图案?

应用程序和 Activity 中的 Android Crittercism init

c++ - 关于我应该为 Visual Studio 和 Eclipse 使用什么单元测试框架的任何想法(红色代码)

c++ - 如何检测当前输入的语言?

java - 对象到对象转换的设计模式是什么?

design-patterns - 异常处理策略——重用异常代码

c++ - C++中的左大括号 "{"错误

c++ - Floyd 的循环查找算法

Java单例内部类

c++ - 神级的替代品