你能否真正搞定单例?

      笔试面试让写个单例,不一定每个人都能搞出来。我们以前也谈论过单例,现在继续来看看:

      可以写为:

 

#include <iostream>
using namespace std;

class A
{
private:
	int x;
	static A *pInstance;

public:
	void set(int m)
	{
		x = m;
	}

	int get()
	{
		return x;
	}

	static A *getInstance();
};

A * A::getInstance()
{
	static A *pInstance = NULL;
	if(NULL == pInstance)
	{
		pInstance = new A;
	}

	return pInstance;
}


int main()
{
	A *p1 = A::getInstance();
	A *p2 = A::getInstance();

	if(p1 == p2)
	{
		cout << 1 << endl;
	}
	else
	{
		cout << 0 << endl;
	}

	return 0;
}

      

 

         但是,下面有错:

 

#include <iostream>
using namespace std;

class A
{
private:
	int x;
	static A *pInstance;

public:
	void set(int m)
	{
		x = m;
	}

	int get()
	{
		return x;
	}

	static A *getInstance();
};

static A * A::getInstance()
{
	static A *pInstance = NULL;
	if(NULL == pInstance)
	{
		pInstance = new A;
	}

	return pInstance;
}


int main()
{
	A *p1 = A::getInstance();
	A *p2 = A::getInstance();

	if(p1 == p2)
	{
		cout << 1 << endl;
	}
	else
	{
		cout << 0 << endl;
	}

	return 0;
}


       下面也有错:

 

 

#include <iostream>
using namespace std;

class A
{
private:
	int x;
	static A *pInstance;

public:
	void set(int m)
	{
		x = m;
	}

	int get()
	{
		return x;
	}

	static A *getInstance();
};

A * A::getInstance()
{
	pInstance = NULL;
	if(NULL == pInstance)
	{
		pInstance = new A;
	}

	return pInstance;
}


int main()
{
	A *p1 = A::getInstance();
	A *p2 = A::getInstance();

	if(p1 == p2)
	{
		cout << 1 << endl;
	}
	else
	{
		cout << 0 << endl;
	}

	return 0;
}


      奇葩的是,下面也有错:

 

 

#include <iostream>
using namespace std;

class A
{
private:
	int x;
	static A *pInstance;

public:
	void set(int m)
	{
		x = m;
	}

	int get()
	{
		return x;
	}

	static A *getInstance()
	{
		pInstance = NULL;
		if(NULL == pInstance)
		{
			pInstance = new A;
		}

		return pInstance;
	}
};


int main()
{
	A *p1 = A::getInstance();
	A *p2 = A::getInstance();

	if(p1 == p2)
	{
		cout << 1 << endl;
	}
	else
	{
		cout << 0 << endl;
	}

	return 0;
}


     你需要写成如下才好啊:

 

 

#include <iostream>
using namespace std;

class A
{
private:
	int x;

public:
	void set(int m)
	{
		x = m;
	}

	int get()
	{
		return x;
	}

	static A *getInstance()
	{
		static A* pInstance = NULL;
		if(NULL == pInstance)
		{
			pInstance = new A;
		}

		return pInstance;
	}
};


int main()
{
	A *p1 = A::getInstance();
	A *p2 = A::getInstance();

	if(p1 == p2)
	{
		cout << 1 << endl;
	}
	else
	{
		cout << 0 << endl;
	}

	return 0;
}

 

 

       当然,如果你愿意,不用成员变量,而是用成员函数的局部静态变量或者该文件的全局静态变量表示单例,也是可以的。 多尝试,多观察,多总结吧。 我始终觉得,搞得面试,很少人能完全一次搞定这些,我在其内。

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值