繁体   English   中英

单例类和多重继承

[英]Singleton class and multiple inheritance

假设我有以下单例基类:

template <class Derived>
class Singleton
{
  public:

    inline static Derived* get();                       

  protected:

    Singleton();                                  
    ~Singleton();                                     
    static std::unique_ptr<Derived> _uptr;                

  private:

    Singleton(const Singleton&);                          
    Singleton & operator = (const Singleton&);             
};

// Initialize the singleton object.
template <class Derived>
std::unique_ptr<Derived> Singleton<Derived>::_uptr = nullptr;

// Constructor
template <class Derived>
Singleton<Derived>::Singleton() {
}

// Constructor
template <class Derived>
Singleton<Derived>::~Singleton() {
}

// Function: get
template <class Derived>
inline Derived* Singleton<Derived>::get() {
  if(_uptr != nullptr) return _uptr.get();
  std::unique_ptr<Derived> tmp(new Derived());
  _uptr = std::move(tmp);
  return _uptr.get();
}

我有以下派生类:

class Foo : public Singleton <Foo> {
  public:
    int value;     
}

int main() {
  Foo A;
  Foo B;
  A.value = 1;
  B.value = 2;
  A.get()->value = 3;
  cout << A.value << endl;  // we get 1
  cout << B.value << endl;  // we get 2
  cout << A.get()->value() << " " << B.get()->value() << endl;  // we get 3
}

我想知道为什么这三种方法在value上会产生完全不同的输出。 A和B继承相同的单例基数,是否应该返回相同的值? 更具体地说,我想实现一个具有全局范围的类,并且将仅启动一次。

您仍然需要在派生的Singleton类中显式删除(自动创建的)默认构造函数和赋值运算符,以禁止实例化多个实例:

class Foo : public Singleton <Foo> {
public:
    int value;
    delete Foo();
    delete Foo(const Foo&);
    delete Foo& operator(const Foo&);
}

我认为您误解了单例模式。

之所以称为单例,是因为仅允许一个实例。 这是通过将构造函数设为私有来完成的,因此您只能通过get-function创建实例。

因此, Foo AFoo B将是非法的。

您获得错误的值,因为您创建了3个实例-这不是单例。

参见https://en.wikipedia.org/wiki/Singleton_pattern

您的类Foo具有成员变量int value ,以及静态成员变量std::unique_ptr<Foo> _uptr

A.value = 1;        // now A.value == 1 and _uptr == nullptr
B.value = 2;        // now B.value == 2 and _uptr == nullptr
A.get()->value = 3; // now _uptr points to a Foo whose value is 3

有三个Foos和三个值。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM