首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >单例类与多重继承

单例类与多重继承
EN

Stack Overflow用户
提问于 2015-11-30 18:41:31
回答 3查看 993关注 0票数 0

假设我有以下单例基类:

代码语言:javascript
复制
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();
}

我有以下派生类:

代码语言:javascript
复制
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不应该在继承相同的单例基时返回相同的值吗?具体来说,我希望实现一个具有全局范围的类,并且只启动一次。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2015-11-30 19:08:34

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

代码语言:javascript
复制
class Foo : public Singleton <Foo> {
public:
    int value;
    delete Foo();
    delete Foo(const Foo&);
    delete Foo& operator(const Foo&);
}
票数 1
EN

Stack Overflow用户

发布于 2015-11-30 19:05:40

我想你误解了单身模式。

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

因此,Foo AFoo B是非法的。

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

请参阅pattern

票数 0
EN

Stack Overflow用户

发布于 2015-11-30 19:10:47

Foo有一个成员变量int value,还有一个静态成员变量std::unique_ptr<Foo> _uptr

代码语言:javascript
复制
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和三个价值观。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34005636

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档