1

可能重复:
不可全局访问的单例

您是否知道一种好的设计模式,它可以确保只创建一个对象的一个​​实例而不使该对象在 C++ 中成为全局对象?这就是单例所做的,但出于代码访问安全原因,我真的不需要它是全局的。

谢谢你的帮助!

4

4 回答 4

2

我想你想要这样的东西(注意:从我已经写过但忘记的答案中复制粘贴):

#include <stdexcept>

// inherit from this class (privately) to ensure only
// a single instance of the derived class is created
template <typename D> // CRTP (to give each instantiation its own flag)
class single_instance
{
protected: // protected constructors to ensure this is used as a mixin
    single_instance()
    {
        if (mConstructed)
            throw std::runtime_error("already created");

        mConstructed = true;
    }

    ~single_instance()
    {
        mConstructed = false;
    }

private:
    // private and not defined in order to
    // force the derived class be noncopyable
    single_instance(const single_instance&);
    single_instance& operator=(const single_instance&);

    static bool mConstructed;
};

template <typename T>
bool single_instance<T>::mConstructed = false;

现在,如果多次构造该类,则会出现异常:

class my_class : private single_instance<my_class>
{
public:
    // usual interface (nonycopyable)
};

int main()
{
    my_class a; // okay
    my_class b; // exception
}

但是,没有办法在 C++ 的编译时强制执行单实例策略。


(你也很高兴注意到单例是愚蠢的。全局可访问和可单独创建是两个不同的概念,只能巧合,而不是设计。)

于 2011-12-24T00:36:34.427 回答
1

You could use a singleton with a typical static Instance() access function, but make this function private. Access is then only granted to another class, by making it a friend classes of the singleton class.

于 2011-12-24T00:08:34.803 回答
0

Make the constructor(s) and assignemnt operator private.

Then make the only function that create the one instance of your class a friend of the class.
Since you are writing the function it is the only one that can create the object (and there will be no others in the application).

于 2011-12-24T00:09:14.660 回答
0

您可以使用命名空间和/或嵌套和本地类来控制对单例类/实例方法的可见性

单例教程 http://www.yolinux.com/TUTORIALS/C++Singleton.html

本地类示例 http://www.informit.com/guides/content.aspx?g=cplusplus&seqNum=191

于 2011-12-24T00:12:58.910 回答