《More Effective C++》学习心得(七) 构造函数私有化

一.只允许一个对象的生成

每当产生一个对象,就会有一个构造函数被调用,如果“阻止某个class产出对象”,最简单的办法就是将其constructors 声明为private:

#include <iostream>    
using   namespace  std; 
将构造函数私有化可以"阻止某个class对象的生成"
法一:建立fried函数可以允许生成唯一的一个class对象
class Print
{
public:
	void submitJob()
	{
		cout<<this<<":Print::submitJob()\n";
	}
	void reset()
	{
		cout<<this<<":Print::reset()\n";
	}
	void performSelfTest()
	{
		cout<<"Print::performSelfTest()\n";
	}
	friend Print & thePrint();
protected:
private:
	Print()
	{
		cout<<"Print::Print()\n";
	}
	Print(const Print &rhs)
	{
		cout<<"Print::copy Print()\n";
	}
};
Print& thePrint()
{
	static Print p;
	return p;
}
int  main() {   
	thePrint().reset();
	thePrint().submitJob();
}


此设计有3个成分:第一.,将Print class 的constructors声明为private,压制对象的产生。第二,全局函数thePrint声明为class的一个friend友元,致使thePrint不受private属性的约束。第三,thePrint函数中内含一个static Print对象,意思是只有一个Print对象会被产生。

书中还有另一种方法,就是将thePrint函数设置为class 的一个static 函数,但是这么做不好,书中声明:“函数拥有一个static对象”比“class拥有一个static对象”的优势在于,“class拥有一个static对象”即使从未被用到,他也会被构造(及析构),而“函数拥有一个static对象”只在函数第一次被调用才产生static对象。

 

二.pseudo constructor(伪构造函数)

#include <iostream>
#include <memory>
using   namespace  std; 
class Print
{
public:
	void submitJob()
	{
		cout<<this<<":Print::submitJob()\n";
	}
	void reset()
	{
		cout<<this<<":Print::reset()\n";
	}
	void performSelfTest()
	{
		cout<<"Print::performSelfTest()\n";
	}
	//pesudo constructor
	static Print* makePrint()
	{
		return new Print();
	};
	//pesudo copy constructor
	static Print* makePrint(const Print &rhs)
	{
		return new Print(rhs);
	};
protected:
private:
	Print()
	{
		cout<<"Print::Print()\n";
	}
	Print(const Print &rhs)
	{
		cout<<"Print::copy Print()\n";
	}
};

int  main() {   
	//为了避免内存泄露,使用智能指针
	auto_ptr<Print> pA(Print::makePrint());
}


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值