c# - 如何在 C++ 中编写 Jon Skeet 的 Singleton?

标签 c# c++ singleton

在乔恩的 site 上他在 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();
    }
}

我想知道如何用 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();

最佳答案

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

关于c# - 如何在 C++ 中编写 Jon Skeet 的 Singleton?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1648689/

相关文章:

c# - 由于其保护级别而无法访问

c++ - unordered_set 与链表查找之间的性能比较

c++ - MFC中如何在非矩形窗口中绘制边框

Angular 2 : how to force an injectable to be a singleton in the app

c# - 将新联系人添加到现有联系人组 ews api

c# - for循环中的sql

c# - 如何获取 IsolatedStorage 中文件的路径?

c++ - 使用occi在c++中连接到oracle 10g时出现ora 24960错误

java - Guice 在急切的单例中命名注入(inject)

php - js中的模块和php中的类有什么区别?