可以在 C++ 中创建单例结构吗?如何?

2024-02-01

当我了解更多关于编码的知识时,我喜欢进行尝试。我有一个程序,在其运行时的生命周期中只需要一个结构的单个实例,并且想知道是否可以创建一个单例结构。我在互联网上看到很多有关创建单例类的信息,但没有看到有关创建单例结构的信息。这可以做到吗?如果是这样,怎么办?

提前致谢。哦,顺便说一句,我是用 C++ 工作的。


A class and 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();
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

可以在 C++ 中创建单例结构吗?如何? 的相关文章

随机推荐