Remember:
- APIs often require access to raw resources, so each RAII class should provide a means to "get the resources it manages".
- Access to the original resource may be transformed by a display or by an implicit conversion. Generally speaking, conversion is more secure, but implicit conversion is more convenient for customers.
Std::tr1::shared_ptr<investment> PINV (Createinvestment ()); int daysheld (const investment* pi); int // Error int days = Daysheld (PINV. Get// correct, both shared_ptr and Auto_ptr provide a GET member function that returns the internal raw pointer.
The
Tr1::shared_ptr and auto_ptr overload the pointer-to-value operators (operator-> and operator*), which allow implicit conversion to internal raw pointers.
class investment{public: boolconst; };investment* createinvestment (); std::tr1::shared_ptr<Investment> pi1 ( Createinvestment ()); bool taxable1 =! (Pi1->istaxfree ()); // access resources via operator-> ... std::auto_ptr<Investment> pi2 (Createinvestment ()); BOOL // access resources via operator* ...
fonthandle GetFont ();voidReleasefont (Fonthandle FH);classFont { Public: ExplicitFont (Fonthandle fh): F (FH) {}~Font () {Releasefont (f);} FonthandleGet()Const{returnF }//Show Conversion Functions operatorFonthandle ()Const //Implicit conversion Functions{returnF;}Private: Fonthandle F;}//using the Display conversion functionvoidChangefontsize (Fonthandle F,intnewSize); Font f (GetFont ());intnewfontsize;...changefontsize (F.Get(), newfontsize);//using an implicit conversion functionFont F (GetFont ());intnewfontsize...changefontsize (f, newfontsize);//using implicit conversion functions increases the chance that an error will occur.Font F1 (GetFont ()); Fonthandle F2= F1;//when you want to copy a Font object, you implicitly convert F1 to Fonthandle, and then copy it. //If the F1 is destroyed, the font is released, and the F2 becomes a virtual hanging object.
Effective C + + clause 15: Provide access to the original resource in the resource management class