2

我试图理解单例对象和静态类之间的区别

我到处看到的最简单的信息是静态类不创建实例,而单例需要

但是为什么我可以从静态类中获得静态构造函数呢?这意味着什么?它不创建一个实例吗?

如果您在静态类构造函数上运行带有断点的简单代码,您将看到它到达它

我很困惑,有人吗?

4

2 回答 2

4

但是为什么我可以从静态类中获得静态构造函数呢?这意味着什么?它不创建一个实例吗?

No. The static constructor allows you to initialize static members of the class (basically, the static state for that class).

With the singleton pattern, the static constructor (or a static inline initializer) often creates an instance, but that instance is still created via the normal, non-static constructor. It's then stored within a static variable (the single "instance" variable).

Lazy-initialized singletons will avoid that, and initialize the static variable on demand.

A static class is a different thing - a static class will never work as a singleton, since you can't create an instance of a static class. Static classes are specifically intended to be used when you will never create an instance.

单例将(通常)通过非静态类创建,但使用私有构造函数(因此只能在该类中创建实例)。将有一个静态属性用于检索该类的单个实例。类实例将按需创建或在静态构造函数中创建。

于 2013-10-07T21:14:19.427 回答
1

静态构造函数只是一个可以初始化静态成员变量的地方。您不需要静态构造函数 - 您可以内联初始化静态成员变量,但我认为将它们放在静态构造函数中更整洁。

请记住,即使您不实例化静态类,您也确实实例化了它的静态成员,并且有一个地方可以这样做是件好事。这是对您必须在 C++ 中执行此操作的方式的改进。

请注意,您的类不需要是静态的才能拥有静态构造函数。您可以拥有一个同时提供普通构造函数和静态构造函数的非静态类。同样的规则适用。

于 2013-10-07T21:19:07.010 回答