c++ - 在 C++ 类中初始化单例

标签 c++ singleton

<分区>

我有一个单例 A,我将在整个 B 类中使用它,因此在多个方法中使用 A::getInstance() 比尝试将引用 A& ref_ 存储到该单例中并没有多大意义只需调用 ref_ 的方法即可。问题是:当所有构造函数、复制构造函数、复制赋值运算符都是私有(private)的时,我如何获取和存储 A&ref_?我将如何解决这个问题?

--丹尼尔。

最佳答案

The problem is: how do I get and store A& ref_, when all constructors, copy constructors, copy assignment operators are private?

考虑一下:

class A { // singleton
    A(); // private
public:
    static A& GetInstance() { // public singleton instance accessor
        static A instance; // initialized on first call to GetInstance
        return instance;
    }
};

class B {
     A& ref;
public:
    B(): ref( A::GetInstance() ) {} // ref now points to the singleton instance
};

也就是说,请尽量不要在代码中使用单例。单例是一种增加模块相互依赖性的设计模式,使代码更加单一且更难测试。

更好的解决方案可能是这样的:

class A { // NOT a singleton
public:
    A(); // public
};

class B {
     A& ref;
public:
    B(A& aref): ref( aref ) {} // ref now points to the injected instance
                               // but doesn't impose that A::GetInstance
                               // exists (aref is dependency-injected)
};

客户端代码:

A& a = [local object or anything else];
B b(a); // now you can inject any A instance and have no imposition
        // in B's implementation that A must be a singleton.

关于c++ - 在 C++ 类中初始化单例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23989129/

相关文章:

objective-c - 如何在 Objective-C 中调试单例

c# - 与单例模式设计中使用的相同类型的类属性

javascript - polymer 中的 MV*,作为 polymer 元素的模型和服务?

C++ 为什么要隐式调用转换器构造函数?

c++ - 在 C++ 中将文件读入内存的最快方法?

c++ - 如果函数模板已经推断出返回类型,有没有办法在不实例化定义的情况下调用它?

grails - Grails范围为Singleton,许多用户登录并执行操作

c++ - 从字符串数据类型的字符串中分离元音并将其存储在新字符串中

c++ - 在 C++ 中查找非元音对

c++ - 模板化单例类 - 如何处理私有(private)构造函数