可能在C ++中创建单例结构?怎么样? [英] Possible to make a singleton struct in C++? How?

查看:88
本文介绍了可能在C ++中创建单例结构?怎么样?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我喜欢实验,因为我了解更多关于编码。我有一个程序,只需要一个结构体的一个实例的运行时的生命,并想知道是否可能创建一个单例结构。我看到很多关于在互联网上制作单例类的信息,但没有做一个单例结构。这可以做吗?如果是,如何?



提前感谢。结构和类在C ++中几乎是一样的(唯一的区别是默认的可见性(默认可见性))。我们使用C + + btw。



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

  struct Singleton 
{
private:
static Singleton * instance;

Singleton()
{
}

Singleton(const Singleton& source)
{
//禁用副本-ctor
}

Singleton(Singleton& source)
{
//停用move-ctor
}

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

return instance;
}
}


I like to experiment around as I learn more about coding. I have a program that would only require a single instance of a struct for the life of it's runtime and was wondering if it's possible to create a singleton struct. I see lot's of information on making a singleton class on the internet but nothing on making a singleton struct. Can this be done? If so, how?

Thanks in advance. Oh, and I work in C++ btw.

解决方案

Struct and class are in C++ almost the same (the only difference is default visibility of members).

Note, that if you want to make a singleton, you have to prevent struct/class users from instantiating, so hiding ctor and copy-ctor is inevitable.

struct Singleton
{
private:
    static Singleton * instance;

    Singleton()
    {
    }

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

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

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

        return instance;
    }
}

这篇关于可能在C ++中创建单例结构?怎么样?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆