條款15:在資源管理類中提供對原始資源的訪問

條款15:在資源管理類中提供對原始資源的訪問
    所有的智能指針都提供一個訪問原始資源的方法,包括:auto_ptr、shared_ptr、boost庫提供的幾種智能指針。
看之前的代碼
class MyLock
{
public:
	explicit MyLock(Mutex *mutex) :m_mutexPtr(mutex, unlock)
	{
		lock(m_mutexPtr.get()); //lock函數需要Mutex的地址,可通過shared_ptr提供的顯示類型轉換函數get()
	}

	//~MyLock() {unlock(m_mutex);}
private:
	std::tr1::shared_ptr<Mutex> m_mutexPtr;

};
shared_ptr和auto_ptr都提供get()成員函數顯示獲取資源指針,而且也重載了->和*符號,用來隱式轉換指針
class Product 
{
public:
	enum {CPU, KEY};

	void SellProduct() {}
};
使用隱式類型轉換調用
        std::tr1::shared_ptr<Product> ptr(GetProduct(1));  
	ptr->SellProduct();  //重載->獲得底層指針
	(*ptr).SellProduct(); //重載*獲得底層對象</span>
RAII對象內的資源
       如何去獲取RAII對象內的資源?這需要自己去定義接口
顯示類型轉換接口,get
class FontHandls {};
void releaseFont(FontHandls * fh) {}
class Font
{
public:
	explicit Font(FontHandls *fh) : m_fontHandls(fh) {}
	~Font() {releaseFont(m_fontHandls);}
	FontHandls *get() const {return m_fontHandls;} 
private:
	FontHandls *m_fontHandls;
};
隱式轉換接口,實現對應的重載操作符
class FontHandls {};
typedef FontHandls* FontPtr;
void releaseFont(FontHandls * fh) {}
class Font
{
public:
	explicit Font(FontHandls *fh) : m_fontHandls(fh) {}
	~Font() {releaseFont(m_fontHandls);}
	//FontHandls *get() const {return m_fontHandls;} 
	operator FontPtr (){return m_fontHandls;}  //重載自定義類型,隱式轉換成內部指針
	FontHandls *operator ->() const{ return m_fontHandls;} //隱式轉換
	FontHandls operator *() const {return *m_fontHandls;}  //隱式轉換
private:
	FontHandls *m_fontHandls;
};

void OperateFont(FontHandls *fh) {};
調用
	FontHandls *fh;
	Font f(fh);

	OperateFont(f);
對應RAII對象資源隱式轉換可能會出現的隱藏問題
	FontHandls *fh;
	Font f(fh);

	FontHandls *fh2 = f;  //願意是想拷貝Font對象,內部實際是轉換爲FontHandls*返回</span>

記住
①API 通常需要訪問原始資源,因此每個 RAII 類都應該提供一個途徑來獲取它所管理的資源。
②訪問可以通過顯式轉換或隱式轉換來實現。一般情況下,顯式轉換更安全,但是隱式轉換對於客戶端程序員來說使用更方便。

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