シングルトンについて、使用すべき場合と使用すべきでない場合、および安全に実装する方法について多くのことを読んできました。私はC++ 11で書いていますが、この質問に見られるように、シングルトンのマイヤーの遅延初期化実装に出くわしました。
この実装は次のとおりです。
static Singleton& instance()
{
static Singleton s;
return s;
}
SOに関する他の質問から、これがスレッドセーフであることは理解していますが、理解できないのは、これが実際にシングルトンパターンである方法です。私は他の言語でシングルトンを実装しましたが、これらは常にウィキペディアの次の例のようになります。
public class SingletonDemo {
private static volatile SingletonDemo instance = null;
private SingletonDemo() { }
public static SingletonDemo getInstance() {
if (instance == null) {
synchronized (SingletonDemo .class){
if (instance == null) {
instance = new SingletonDemo ();
}
}
}
return instance;
}
}
この 2 番目の例を見ると、クラスがそれ自体の 1 つのインスタンスへの参照を保持し、そのインスタンスのみを返すため、これがシングルトンであることが非常に直感的です。ただし、最初の例では、オブジェクトのインスタンスが 2 つ存在しないようにする方法がわかりません。だから私の質問は:
- 最初の実装では、シングルトン パターンをどのように強制しますか? static キーワードに関係していると思いますが、内部で何が起こっているのかを誰かが詳しく説明してくれることを願っています。
- これら 2 つの実装スタイルのうち、どちらが望ましいでしょうか? 長所と短所は何ですか?
助けてくれてありがとう、