【问题标题】:Singleton-Inheritance C++ Implementation [duplicate]单例继承 C++ 实现
【发布时间】:2015-09-15 11:51:57
【问题描述】:

我正在尝试实现模板单例模式,但出现以下错误。我应该如何克服这个错误?

下面是singleton_template.h

#include <iostream>
#include <string>
/*
* Burada yapılan herşey ".h" dosyası içerinde olmalı
*/
template<typename T>
class Singleton
{
private:
   static T* _instance;
   Singleton(const Singleton&);
   Singleton & operator=(const Singleton& rhs);

protected:
   Singleton();

public:
   static T* getInstance()
   {
     if(!_instance)
     _instance = new T;
     return _instance;
   }

   void destroyInstance()
   {
       delete _instance;
       _instance = NULL;
   }
};

template<typename T>
T* Singleton<T>::_instance= NULL;

这里是 singleton_template.cpp

#include <iostream>
#include <string>
#include "singleton_template.h"

class GKM : public Singleton<GKM>
{
public:

  GKM()
  {
    std::cout << "Single GKM created"<<std::endl;
  }
  virtual void initialize(){return;}

};

class Turnstile: public GKM 
{
public:
  Turnstile(){std::cout << "Single turnstile created add: "<< this<<std::endl;}
  virtual void initialize(){std::cout <<"Turnstile"<< std::endl;}

};

int main()
{
  GKM* trn= Turnstile::getInstance();
  trn->initialize();
  return 0;
}

这是编译失败后得到的结果:

/tmp/ccfD0Xgx.o:在函数GKM::GKM()中: singleton_template.cpp:(.text._ZN3GKMC2Ev[_ZN3GKMC5Ev]+0xd): 未定义 参考Singleton&lt;GKM&gt;::Singleton()collect2:错误:ld 返回 1 个退出状态

【问题讨论】:

  • 您应该阅读here 了解更常见的成语。使用new T 会证明不是线程安全的。
  • 天哪,这不是线程安全的!

标签: c++ templates inheritance polymorphism singleton


【解决方案1】:

您没有实现Singleton 类的默认构造函数,这是您需要的,因为您将Singleton 类作为子类。你可以改变

Singleton();

行到

Singleton() {}

但是,当我阅读您的代码时,它无论如何都不会按预期工作,因为

GKM* trn= Turnstile::getInstance();

实际上只创建GKM 对象,而不是Turnstile,因为您将Singleton 模板化在GKM 上,而不是Turnstile。 (或者这是故意的?)

【讨论】:

  • 谢谢 Petr,它很快就会编译。正如您提到的,它刚刚创建了GKM。如何从 GKM 类创建单个 turnstile 对象
  • @Nuri,有很多(或没有)方法可以从 GKM 对象创建 Turnstile,具体取决于您想要实现的目标。我建议你问一个单独的问题来描述你真正想要实现的目标(不仅仅是“从GKM 创建一个Turnstile”,而是你为什么真的需要这个,你为什么要尝试使用单例呢? ,你想在你的程序中有什么)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-17
  • 2012-04-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多