title: Reference Counting in C++
body: <p>I'm implementing a math library in C++. The library will be compiled to a DLL so those who use it will only need the header files the classes' definitions.</p>
  
  <p>The users of my classes will be people who are new to the language. However, there are some objects that might be referenced in several parts of their programs. Since I don't expect them to do the memory management, I'd like to do it myself. Therefore, I have to implement reference counting (garbage collection is not a possibility).</p>
  
  <p>I want to make that reference counting as transparent as possible, for example...</p>
  
  <pre><code>// 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;
  </code></pre>
  
  <p>Things get a little bit more tricky when I define surface objects, because some surfaces are defined in terms of two curves:</p>
  
  <pre><code>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
  </code></pre>
  
  <p>I thought that overriding <code>operator =</code> for pointers could have helped:</p>
  
  <pre><code>// This is what I tried, but it's illegal:
  typedef CReferenceCounted* PRC;
  PRC&amp; operator =(PRC&amp; dest, PRC&amp; source)
  {
      if (source)
          source-&gt;AddRef();
      if (dest)
          dest-&gt;Release();
      memcpy(&amp;dest,&amp;source,sizeof(PRC));
      return dest;
  }
  </code></pre>
  
  <p>... but then I found that <code>operator =</code> is not valid unless it is as a non-static member of a class.</p>
  
  <p>Could anybody possible help me?</p>