条款15 在资源管理类中提供对原始资源的访问

#include<iostream>
#include<string>
#include<memory>//智能指针
using namespace std;
class Resouce{
public:
	Resouce(){
		cout << "Resouce()" << endl;
	}
	~Resouce(){
		cout << "~Resouce()" << endl;
	}
	void dosomething(){
		cout << "dosomething" << endl;
	}
};
class Base{
public:
	void fun(){
		auto_ptr<Resouce>raii(new Resouce);/*RAII 资源取得时机便是初始化时机*/
	}
private:
};
class Derived :public Base{
public:
	//..
	Derived(){}

private:
	int m_i;
};
void CAPI(const Resouce*pi){
	cout << "do something" << endl;
}
void test(){
	auto_ptr<Resouce>r1(new Resouce);
	auto_ptr<Resouce>r2(new Resouce);
	shared_ptr<Resouce>r3(new Resouce);
	shared_ptr<Resouce>r4(new Resouce);
//	CAPI(r4);//r4的类型为shared_ptr<Investment>的对象
	CAPI(r4.get());//shared_ptr auto_ptr都提供了一个get成员函数,用来执行显示转换,也就是它返回智能指针内部的原始指针(的复件)
}
//----------------------------
class FontHandle{

};
void releaseFont(FontHandle fh){}
FontHandle getFont(){
	FontHandle a;
	return  a;
}
class Font{//RAII class
public:
	Font(){}
	explicit Font(FontHandle fh) :f(fh){

	}
	~Font(){
		releaseFont(f);
	}
	//如果有大量与字体相关的CAPI,将Fond对象转换成FontHandle将很频繁,可以提供一个显示转换函数像shared_ptr 那样
	FontHandle get()const{//显示转换函数
		return f;
	}
	operator FontHandle()const{//隐式类型转换
		return f;
	}
private:
	FontHandle f;
};
int newFontSize;
void changeFontSize(FontHandle f, int newSize){

}
void test2(){
	Font f;
	changeFontSize(f.get(), newFontSize);
	changeFontSize(f ,newFontSize);

}
int main(){
	Base b;
	b.fun();
	test();
	//----------------------

	system("pause");
	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值