C ++这个类和单例的全局声明有什么好的替代方法吗?

C++ Are there any good alternatives to global declaration of this class and singleton?

本问题已经有最佳答案,请猛点这里访问。

如何在没有singleton的情况下生成此类的单个实例,以及如何声明它,以便另一个类可以在不全局声明的情况下访问它?

请阅读代码(尤其是注释),以便更好地理解:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <iostream>
#include <vector>

// The only class that will be using this class is Obj...
// There can only be a single instance of ObjManager but how can I do that
// without singleton???
class ObjManager
{
    friend class Obj;
    int i;
};

// Since I cannot think of a better way of accessing the SAME and ONLY ObjManager, I
// have decided to declare a global instance of ObjManager so every instance of
// Obj can access it.
ObjManager g_ObjManager;

class Obj
{
    friend class ObjManager;
public:
    void Set(int i);
    int Get();
};

void Obj::Set(int i) {
    g_ObjManager.i += i;
};

int Obj::Get() {
    return g_ObjManager.i;
};

int main() {
    Obj first_obj, second_obj;

    first_obj.Set(5);
    std::cout << second_obj.Get() << std::endl; // Should be 5.
    second_obj.Set(10);
    std::cout << first_obj.Get() << std::endl; // Should be 15.

    std::cin.get();
    return 0;
};


为什么不这样:

1
2
3
4
5
6
7
8
9
10
11
12
13
class ObjManager
{
private:
    ObjManager() {}

public:
    static ObjManager& get() {
        static ObjectManager m;
        return m;
    }
    friend class Obj;
    int i;
};

然后打电话给ObjManager::get获取参考。作为奖励,只有在您实际使用它时才会构建它。它仍然是单件的,但比全球性的要好一点(在我看来)。


如果希望所有Obj实例共享同一ObjManager实例(而不希望使用单例模式创建ObjObjManager实例),可以在Obj中创建ObjManager的静态成员:

1
2
3
4
5
6
7
class ObjManager { ... };

class Obj
{
private:
   static ObjManager manager;
};

然后,当您创建一个Obj的实例时,它将与所有其他实例共享同一个ObjManager