我正在用 C++ 实现一个数学库。该库将被编译为 DLL,因此使用它的人只需要类定义的头文件。
我的课程的用户将是刚接触这门语言的人。但是,有些对象可能会在其程序的几个部分中被引用。因为我不希望他们做内存管理,所以我想自己做。因此,我必须实现引用计数(垃圾收集是不可能的)。
我想让引用计数尽可能透明,例如......
// Define a Bézier curve
CVecList pts;
pts.Add(Vector(0,0,0));
pts.Add(Vector(0,0,100));
pts.Add(Vector(0,100,0));
pts.Add(Vector(0,100,100));
CCurve* c1 = new CBezier(pts);
// Define a 3rd order B-Spline curve
pts.Clear();
pts.Add(Vector(0,0,0));
pts.Add(Vector(0,200,100));
pts.Add(Vector(0,200,200));
pts.Add(Vector(0,-200,100));
pts.Add(Vector(0,-200,200));
pts.Add(Vector(0,0,0));
CCurve* c2 = new CBSpline(pts,3);
// The Bézier curve object must be deleted automatically
// because the only reference to it has been released
// Similar to IUnknown::Release() in COM
c1 = c2;
当我定义曲面对象时,事情变得有点棘手,因为有些曲面是根据两条曲线定义的:
CVecList pts;
// ...
CCurve* f = new CBezier(pts);
pts.Clear();
// ...
CCurve* g = new CBezier(pts);
// Mixed surface: S(u,v) = (1-v)*f(u) + v*g(u)
CSurface* s = new CMixed(f,g);
// There are two references to the first Bézier curve,
// the first one is f
// the second one is hidden in a member of CMixed
// Something similar applies to the second Bézier curve
我认为覆盖operator =
指针可能会有所帮助:
// This is what I tried, but it's illegal:
typedef CReferenceCounted* PRC;
PRC& operator =(PRC& dest, PRC& source)
{
if (source)
source->AddRef();
if (dest)
dest->Release();
memcpy(&dest,&source,sizeof(PRC));
return dest;
}
...但后来我发现这operator =
是无效的,除非它是类的非静态成员。
有人可以帮助我吗?