📄 mainwzproxytest.html
字号:
<TITLE>WZ 1.1: Proxies</TITLE><H1>template wzProxy</H1> <P>The template <B>wzProxy</B> implements safe pointers - they may beused like pointers, but manage access control (deallocation). To usethis template, you have to make your target class <I>ObjectClass</I>a derived class of <B>wzProxyTarget</B>. <P><B>wzProxyTarget</B> contains a counter which counts the number ofsafe pointers pointing to this object.<PRE>#include "<A HREF="wzsafepointer.hxx">wzsafepointer.hxx</A>"class ObjectClass: public wzProxyTarget{public: int i; operator int() {return i;} const ObjectClass& operator=(const int& i0) {i=i0; return *this;} const ObjectClass& operator=(const ObjectClass& i0) {i=i0.i; return *this;} ObjectClass(int i0):i(i0){;}};</PRE> <P>Now you can declare your "safe pointer class" <I>PointerClass</I>in the following way:<PRE>typedef wzProxy<ObjectClass> PointerClass;</PRE> <P>Now, see yourself what is allowed here for the "safe pointers":<PRE>void main(){ PointerClass y,z,z1,z2; { PointerClass x = new ObjectClass(10); ObjectClass& r1 = *(new ObjectClass(99)); ObjectClass r2(138); PointerClass z2; now(x->accessCount()==1); y = x; now(x->accessCount()==2); (*x)=3; now(*y==3); now(r1.accessCount()==0); now(r2.accessCount()==0); z1 = &r1; z2=&r2; z=&r1; now(r1.accessCount()==2); now(r2.accessCount()==1); now(*z1==99); now(*z2==138); r1 = r2; now(*z1==138); now(r1.accessCount()==2); now(r2.accessCount()==1); now(y->accessCount()==2); } now(y->accessCount()==1);</PRE> <P>Note that it is allowed to get addresses of local variables - avery unsafe operation. The point is that it will be detected at runtime if you make errors here.<gA NAME="errors"> <hr></A><H2><A HREF="errors.html">Errors</A></H2><H3><A NAME="ProxyHangingError">ProxyHangingError</A></H3> <P>Because it is allowed to get the address of a local variable ofthe object class, there may be pointers to the local variable at themoment of destruction. The classical error is the following:<PRE> try{ PointerClass x; { ObjectClass X(11); x = &X; // that's ok yet; now(*x==11); // indeed, no problem; // x = 0; before closing the block, you have to reset the address; } // without this, *x becomes an invalid pointer to non-existing memory; should_fail(); // but this immediately causes an exception! }catch(wzProxyHangingError){;}</PRE><A NAME="End"> <hr></A> <P>You can test this code with: <BR> <BR><B>>cog main wzproxy</B> <BR> <BR>The output should be simply: <BR> <BR><B>success</B><PRE> fine();}</PRE>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -