1

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

提前致谢。哦,我在 C++ 中工作。

4

5 回答 5

8

Aclass和 astruct几乎是一回事,除了一些小细节(例如其成员的默认访问级别)。因此,例如:

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();
}
于 2013-03-03T15:38:41.410 回答
3

结构和类在 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:
    Singleton * GetInstance()
    {
        if (instance == nullptr)
            instance = new Singleton();

        return instance;
    }
}
于 2013-03-03T15:41:04.373 回答
2

从概念上讲,astruct和 aclass在 C++ 中是相同的,因此制作单例与制作单例struct相同class

class和之间的唯一区别struct是默认访问说明符和基类继承:privateforclasspublicfor struct。例如,

class Foo : public Bar 
{ 
 public: 
  int a;
};

是相同的

struct Foo : Bar
{
 int a;
};

因此,在单例方面没有根本区别。请务必阅读为什么单身人士被认为是坏的

这是一个简单的实现:

struct singleton
{
  static singleton& instance()
  {
    static singleton instance_;
    return instance_;
  }
  singleton(const singleton&)=delete;            // no copy
  singleton& operator=(const singleton&)=delete; // no assignment

 private:
  singleton() { .... } // constructor(s)
};
于 2013-03-03T15:38:56.450 回答
1

首先,struct仅指class成员的默认访问权限。你可以用一个结构来做任何你可以用一个类来做的事情。现在,如果您指的是 POD 结构,事情会变得更加复杂。您无法定义自定义构造函数,因此无法仅强制创建单个对象。但是,没有什么能阻止您仅将其实例化一次。

于 2013-03-03T15:39:49.163 回答
0

class并且几乎struct是C++ 中的同义词。对于单例用例,它们是完整的同义词。

于 2013-03-03T15:39:50.283 回答