没想通为何这个简单实验中总打印不同地址 - 单例模式

执假以为真 2013-05-19 09:39:32
看代码:

#include <iostream>
using namespace std;

class Singleton {
public:
static Singleton * GetInstance() { return _pInstance == 0 ? (new Singleton) : _pInstance;}

private:
Singleton() {}
~Singleton() {delete _pInstance;}

private:
static Singleton * _pInstance ;
};

Singleton * Singleton::_pInstance = 0;

int main(void)
{
cout<<"The point of instance is " <<hex <<Singleton::GetInstance() <<endl;
cout<<"The point of instance is " <<hex <<Singleton::GetInstance() <<endl;
cout<<"The point of instance is " <<hex <<Singleton::GetInstance() <<endl;

cout<<"Size of Singleton is " <<hex <<sizeof(Singleton) <<endl; // 1
return 0;
}


前三条cout语句是期待打印同样的地址,为何每次会不一样呢?
...全文
144 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
shun_qizi_ran 2013-05-19
  • 打赏
  • 举报
回复
每次都是返回了一个新创建的实例,要把第一次创建的实例赋值给_pInstance 才行 试试:

static Singleton * GetInstance() { 
    return _pInstance == 0 ? (_pInstance = new Singleton) : _pInstance;
 }
x363635334 2013-05-19
  • 打赏
  • 举报
回复
楼上正解,楼主成员变量是摆设
执假以为真 2013-05-19
  • 打赏
  • 举报
回复
哦,哈哈,是的。
执假以为真 2013-05-19
  • 打赏
  • 举报
回复
没看懂,为何不加_pInstance = this这一句就会似乎每次都new一个出来呢? 难道那个是否等于0的判断白做了吗?
taodm 2013-05-19
  • 打赏
  • 举报
回复
瀑布狂汗。 楼主new了之后没赋给 _pInstance
lunat 2013-05-19
  • 打赏
  • 举报
回复
Singleton() { _pInstance = this; }

64,666

社区成员

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

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