帮我看看单例模式有啥问题?

ybxuwei 2014-10-29 06:38:52
#include <memory>
#include <iostream>

using namespace std;

template<class T>
class Singleton
{
public:
static T *Instance()
{
if(instance_.get() == NULL)
instance_.reset(new T);
return instance_.get();
}
virtual ~Singleton(){}
protected:
Singleton(){}
private:
static std::auto_ptr<T> instance_;
};

template<class T>
std::auto_ptr<T> Singleton<T>::instance_;

class T : protected Singleton<T>
{
public:
void print(){cout << "this is a stest" << endl; }
};

int _tmain(int argc, _TCHAR* argv[])
{
T t; // 这样竟然能运行通过
t.print();
// T::Instance()->print();
return 0;
}
...全文
124 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
xyz1991xyz 2014-10-30
  • 打赏
  • 举报
回复
sry,是cls.
xyz1991xyz 2014-10-30
  • 打赏
  • 举报
回复
构造和析构最好都私有化即可避免这一问题。 另外,即使是测试代码,类名写T也是不明智的,图省事推荐写Cla代表class
mymtom 2014-10-30
  • 打赏
  • 举报
回复
单例要把缺省构造函数设置为 private 呀
ybxuwei 2014-10-29
  • 打赏
  • 举报
回复
这只是测试代码,为了省事写成这个,不要太纠结这个。解决一下主要问题吧
勤奋的小游侠 2014-10-29
  • 打赏
  • 举报
回复
class T : protected Singleton<T> { public: void print(){cout << "this is a stest" << endl; } }; 我都 想不明白,你的这个类名为什么还要用T?这样会写代码会比较爽一点吗?

64,281

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧