#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的方式来构造对象,不可以在栈上构造

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

755

被折叠的 条评论
为什么被折叠?



