0

可能重复:
单例有什么不好的?
C++ 中的单例模式

我想创建一个单例类。为此,我创建了一个类,其所有成员和方法都是静态的。像这样的东西。

class a
{
    static int a;
    static GetA();
}

现在所有想要使用我的单例类的类都不能为我的类创建任何对象,并且也将获得相同的值。我只想知道这个实现是否能解决所有目的并满足创建单例类的所有标准。

4

2 回答 2

3

我更喜欢:

GlobalObjectMgr& GlobalObjectMgr::instance()
{
    static GlobalObjectMgr objMgr;
    return objMgr;
}

不需要类成员变量,它仅在需要时创建。

于 2012-07-06T12:24:49.020 回答
2

传统的单例(反)模式不是静态变量的集合;相反,它是一个具有非静态成员的对象,其中只能存在一个实例。

In C++, this allows you to avoid the biggest problem with static variables: the "initialisation order fiasco". Because the initialisation order is unspecified for static variables in different translation units, there's a danger that the constructor of one might try to access another before it is initialised, giving undefined behaviour. However, it introduces other problems (a similar "destruction order fiasco", and thread safety issues in older compilers), so it's still something to avoid.

If you want a collection of static variables and functions, then put them in a namespace rather than a class:

namespace stuff {
    int a;
    void do_something();
}

If you think you want a singleton, then think again; you're generally better avoiding globally accessible objects altogether. If you still want one, then you would make a class with a private constructor, and a public accessor that returns a reference to the single instance, along the lines of:

class singleton {
public:
    singleton & get() {
        static singleton instance;
        return instance;
    }

    int a;
    void do_something();

private:
    singleton() {}
    ~singleton() {}
    singleton(singleton const &) = delete;
};
于 2012-07-06T13:17:58.923 回答