c++ - 我需要一个单例吗?

标签 c++ singleton

我是一名致力于科学代码的物理学家。如果这是一个常规问题,我深表歉意:以前可能已经有人回答过,但我没有软件工程背景可以说清楚。

基本上,代码需要进行大量的矩阵乘法运算 通过少量不同的矩阵。首先构建矩阵非常昂贵,所以我希望它们在使用之间保持不变。但是,进行乘法运算的类无法知道在其初始化期间矩阵将是什么。它们在其生命周期内会发生很大变化,并且相同的矩阵通常会被乘法类的多个实例使用。

在我看来,单例模式适用于这种情况:我们可以创建一个矩阵池,以将它们彼此区分开来的方式作为键。然后,乘法类可以在需要矩阵时访问该池。

这是我的想法的草图:

//SingletonDictionary.hpp
class SingletonDictionary : private NonCopyable {
    public:
        void Clear(); //Calls member variable destructors.
        ~SingletonDictionary() { Clear(); }
    private:
        friend SingletonDictionary& TheSingletonDictionary();
        SingletonDictionary() {}; //Only the friend can make an instance.

        //Retrieve searches through the key vectors for a match to its
        //input. In none is found, the input is added to the key vectors,
        //and a new Value is constructed and added to the ValueVector.
        //In either case the ValueVector is returned.
        std::vector<double>& Retrieve(const int key1, const int key2);

        std::vector<int> mKey1;
        std::vector<int> mKey2;
        std::vector<double> mValue;
}

//SingletonDictionary.cpp
SingletonDictionary& TheSingletonDictionary() {
    static SingletonDictionary TheSingleton;
    return TheSingleton;
}

//DoMatrixMultiply.cpp
void ApplyTransformation(std::vector<double> data){
     const int key1 = data.size()[0];
     const int key2 = data.size()[1];
     SingletonDictionary TheSingletonDictionary();
     std::vector<double> TransformMatrix = 
                      TheSingletonDictionary.Retrieve(key1, key2);
     DGEMM("N", "N", data.Data(), TransformMatrix.Data(),.....);
}

NonCopyable 是一个抽象基类,它禁用复制构造函数等。

我想知道这是否适合这种模式。如果不是,还有什么可能有用?

最佳答案

对于大多数意图和目的而言,单例是带有糖衣的全局变量。全局变量当然有时很有用,但它们也可能是问题的根源(因为没有办法拥有多个实例)。

我个人会考虑拥有一个类来保存这些值(可能是不可复制的),但使其成为实际计算的(引用)成员并且更明确地表明它正在被使用。如果您需要拥有两个(或更多)这些对象,这也将允许您使用多个对象,而不必重写代码来处理这种情况。

关于c++ - 我需要一个单例吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33988735/

相关文章:

c++ - 错误 LNK2019 : unresolved external symbol

c++ - 在 C++ 中可视化 3D 条形图

swift - 如何从继承 nsobject 和 nscoding 的类创建单例类?

javascript - 从任何地方访问 Singleton

c++ - DX11 Sprite 问题

c++ - ICU C++ 转换编码

c++ - C++11 中的尾端迭代器失效

ruby - 为什么 Ruby 模块包含排除了模块的单例类?

c++ - 在大型框架中定义和访问对象

c++ - 如何在单例中传递参数