c++中singleton模式的一种实现方法

博客给出了一段C++代码,实现了一个单例模式的类test。代码中定义了静态指针、构造函数和重载的new运算符。在main函数中多次使用new创建对象进行测试。同时指出该实现的缺点是只能通过new构造对象,不能在栈上构造。

#include<stdio.h>
class test
{
 static test* pInstance;
 protected:
public:
 test()
 {
  if(!pInstance){
      pInstance = 0;
  }
  printf("test init/n");
 }
 void* operator new(unsigned int size)
 {
  if (!pInstance){
   pInstance = (test*)::operator new(sizeof(test));  }
  return (void*)pInstance;
 }
 int aa;
};
test* test::pInstance = NULL;
#ifndef __NO_UNIT_TEST__
int main()
{
 printf("singleton pattern test/n");
 test* pt = new test();
 test * pt2 = new test();
 printf("%d,%d/n",pt->aa,pt2->aa);
 pt->aa=123;
 printf("%d,%d/n",pt->aa,pt2->aa);
 test* pt3 =new test();
 printf("%d,%d,%d/n",pt->aa,pt2->aa,pt3->aa);
 return 0;
}
#endif

缺点:只可以通过new的方式来构造对象,不可以在栈上构造

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值