如何在C++中编写Jon Skeet的Singleton代码?

And*_*rsK 14 c# c++ singleton

在Jon的网站上,他在C#中使用了这个优雅设计的单例,如下所示:

public sealed class Singleton
{
    Singleton()
    {
    }

    public static Singleton Instance
    {
        get
        {
            return Nested.instance;
        }
    }

    class Nested
    {
        // Explicit static constructor to tell C# compiler
        // not to mark type as beforefieldinit
        static Nested()
        {
        }

        internal static readonly Singleton instance = new Singleton();
    }
}
Run Code Online (Sandbox Code Playgroud)

我想知道如何在C++中编写等效代码?我有这个,但我不确定它是否实际上具有与Jon相同的功能.(顺便说一下,这只是一个星期五的练习,不需要任何特别的东西).

class Nested;

class Singleton
{
public:
  Singleton() {;}
  static Singleton& Instance() { return Nested::instance(); }

  class Nested
  { 
  public:
    Nested() {;}
    static Singleton& instance() { static Singleton inst; return inst; }
  };
};

...


Singleton S = Singleton::Instance();
Run Code Online (Sandbox Code Playgroud)

Vij*_*hew 34

这项技术是由马里兰大学计算机科学研究员Bill Pugh引入的,并且已经在Java圈子中使用了很长时间.我认为我在这里看到的是Bill的原始Java实现的C#变体.它在C++上下文中没有意义,因为当前的C++标准对并行性是不可知的.整个想法基于语言保证,即内部类将仅以第一次使用的实例加载,以线程安全的方式加载.这不适用于C++.(另见维基百科条目)


nav*_*tor 9

在本文中,您将找到关于如何实现单例的一个很好的讨论,以及C++中的线程安全性.

http://www.aristeia.com/Papers/DDJ_Jul_Aug_2004_revised.pdf