📄 wzsafepointertest.html
字号:
<TITLE>WZ 1.0 - Safe Pointer</TITLE>
<H1>Safe Pointer</H1>
<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){;}
};
typedef wzProxy<ObjectClass> PointerClass;
void test()
{
</PRE>
<P>
<PRE>
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>
<gA NAME="errors"> <hr></A>
<H2><A HREF="errors.html">Errors</A></H2>
<H3><A NAME="SafePointerHangingError">SafePointerHangingError</A></H3>
<P>Because it is allowed to get the address of a local variable of
the object class, there may be pointers to the local variable at the
moment 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;
} // but now, X will be destroyed as a local variable;
should_fail(); // after this, *x is invalid;
{ObjectClass Y(12); // probably the same address as X;
*x = 123; // this would be the worst case of overwriting Y;
}
}catch(wzProxyHangingError){;}
</PRE>
<H3><A NAME="SafePointerLockError">SafePointerLockError</A></H3>
<P>You can forbid pointer access. In this case, an attempt to do it
throws an exception.
<PRE>
try{PointerClass x;
{ObjectClass X(11);
X.lockPointerAccess();
{{{{{ // somewhere hidden behind a lot of calls, the following happens:
x = &X;
should_fail();
}}}}}}
}catch(wzProxyLockError){;}
</PRE>
<A NAME="End"> <hr></A>
<PRE>
}
</PRE>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -