《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

}


 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章