smart pointer / constructor design problem
I have a standard reference counted smart pointer class abridged as
follows:
class Handleable { int refs; }
template<T> // T is subclass of Handleable
class Handle<T>
{
T* m_p;
Handle(T* p) : m_p(p) { m_p->refs++; }
Handle(Handle<T>& that) : m_p(that.m_p) { m_p->refs++; }
~Handle() { if (m_p->refs-- == 0) delete this; }
}
(Handle also can deal with null pointers and other things but you get
the idea)
The problem is that if a Handle is created and destroyed during
construction of a Handleable object, than the ref count is reduced to
0 and "delete this" fires:
void f(Handle<C> c)
{
...
}
class C : public Handleable
{
C()
{
f(this);
}
}
Handle<C> c = new C(); // crash, f's Handle<C> parameter causes
destruction of C instance before c's constructor can increment ref
count.
I'm trying to think of a nice way around this. Ive considered having
a seperate initializing routine, but that would lose most of the
benefits of constructors. Also considered adding something to
Handleable's constuctor to help avoid this situation, but it looks
messy.
Adding the first Handle<T> to Handleable's constructor is an option...
template <class T>
Handleable::Handleable(Handle<T>& firstHandle)
{
firstHandle = this;
}
This way the first handle would be set before the construction of the
subclass and it would change the syntax as follows:
Handle<C> c; new C(c);
Again this seems messy and slow.
Any ideas?
Thanks.
Andrew.
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]