《More Effective C++》学习心得(八) 要求(或禁止)对象产生于heap中

一。要求对象必须产生于heap中

#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";
	}
	Print()
	{
		cout<<"Print::Print()\n";
	}
	Print(const Print &rhs)
	{
		cout<<"Print::copy Print()\n";
	}
	//pseudo deconstructor
	void desttoy()
	{
		delete this;
	}
protected:
	//将析构函数声明为private会影响继承和内含,所以改为protected
	~Print()
	{
		cout<<"Print::~Print()\n";
	}
private:


};

int  main() {   
//	Print p;  //it's error,because the deconstructor is private
	Print *p1=new Print();
	//delete p1;  //this's also error,because it attempt to invoke the private deconstrutor
	p1->desttoy();

}


虽然书中说也可以见所有构造函数私有,但明显没有将析构函数私有来的简单,原因:析构函数只有一个,二构造函数五花八门(包括拷贝构造函数)。

同样,将析构函数私有带来的致命问题是:妨碍了继承(inheritance)和内含(containment)。

二。禁止对象产生于heap中

#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";
	}

protected:

private:
	static void *operator new(size_t size);
	static void operator delete(void *ptr);



};

int  main() {   
	Print p1;
	static Print p2;
//	Print *p3=new Print();//it's error

}


 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值