【发布时间】: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<GKM>::Singleton()collect2:错误:ld 返回 1 个退出状态
【问题讨论】:
-
您应该阅读here 了解更常见的成语。使用
new T会证明不是线程安全的。 -
天哪,这不是线程安全的!
标签: c++ templates inheritance polymorphism singleton