
On Sunday, July 12, 2009, Ulrich Eckhardt <doomster@knuut.de> wrote:
On Wednesday 08 July 2009 21:33:50 Neil Groves wrote:
On Wed, Jul 8, 2009 at 8:21 PM, Ulrich Eckhardt <doomster@knuut.de> wrote:
On Monday 06 July 2009 17:23:41 Zachary Turner wrote:
Is there a case to be made for a more flexible shared_ptr (either through modification or through a new class addition) that allows one to provide custom reference counting semantics much the same way that shared_ptr allows one to provide custom deletion semantics?
Maybe it's already there: shared_ptr doesn't care if the passed deleter actually deletes anything. If you now take an object with an existing reference count, you just increment that count and pass the function that decrements it as deleter function to a shared_ptr constructor. This creates a parallel reference count, but it should be safe. Nothing can pull the object from under the shared_ptr's feet because it holds a reference. The shared_ptr doesn't destroy the object either, at most it decrements the reference count.
It isn't already there, because unfortunately, in general, this doesn't work. You need the reference count to increase when the shared pointer is copied, for example.
There is no "the reference count", but actually two of them. The internal reference count of the object doesn't increase but the external one, shared by the shared pointers. That external one counts how many shared pointers share a single internal reference.
// first pointer, increases internal refcount intrusive_ptr<InternallyRefcounted> ptr1(raw_ptr);
// increment refcount manually inc_refcount(raw_ptr); // second pointer, living on the above manual reference shared_ptr<InternallyRefcounted> ptr2(raw_ptr, &dec_refcount);
Reset either of ptr1 or ptr2. For the intrusive_ptr, it would decrement the internal reference count. For the shared_ptr, it would decrement its own reference count and if that reaches zero, it would also decrement the object's internal one as part of invoking the deleter.
Should work, unless I'm missing something. Also, I'm not 100% sure that this is what the OP is actually looking for.
Uli
It does work. I've used this technique before with some internally ref counted that I inherited. Tony