可以在C++中创建单例结构吗?怎么样?

Jak*_*ake 1 c++ singleton struct

随着我对编码的了解越来越多,我喜欢尝试一下.我有一个程序,它只需要一个结构的单个实例来维持它的运行时间,并且想知道是否可以创建一个单例结构.我看到很多关于在互联网上制作单例类的信息,但没有关于制作单例结构的信息.可以这样做吗?如果是这样,怎么样?

提前致谢.哦,我用C++工作.

And*_*owl 7

除了一些小细节(例如其成员的默认访问级别)之外,A class和a struct几乎是相同的.因此,例如:

struct singleton
{
    static singleton& get_instance()
    {
        static singleton instance;
        return instance;
    }

    // The copy constructor is deleted, to prevent client code from creating new
    // instances of this class by copying the instance returned by get_instance()
    singleton(singleton const&) = delete;

    // The move constructor is deleted, to prevent client code from moving from
    // the object returned by get_instance(), which could result in other clients
    // retrieving a reference to an object with unspecified state.
    singleton(singleton&&) = delete;

private:

    // Default-constructor is private, to prevent client code from creating new
    // instances of this class. The only instance shall be retrieved through the
    // get_instance() function.
    singleton() { }

};

int main()
{
    singleton& s = singleton::get_instance();
}
Run Code Online (Sandbox Code Playgroud)

  • @StoryTeller:正确.谢谢你指出. (2认同)
  • @Spook:正确.我忘了添加`static`关键字.我只在脑海里这样做过.编辑,谢谢. (2认同)

Spo*_*ook 6

C++ 中的结构体和类几乎相同(唯一的区别是成员的默认可见性)。

注意,如果你想创建一个单例,你必须阻止struct/class用户实例化,所以隐藏ctor和copy-ctor是不可避免的。

struct Singleton
{
private:
    static Singleton * instance;

    Singleton()
    {
    }

    Singleton(const Singleton & source)
    {
        // Disabling copy-ctor
    }

    Singleton(Singleton && source)
    {
        // Disabling move-ctor
    }

public:
    static Singleton * GetInstance()
    {
        if (instance == nullptr)
            instance = new Singleton();

        return instance;
    }
}
Run Code Online (Sandbox Code Playgroud)