this on reference counted objects

A

Arne Claus

Hello
I've written a usefull little smartpointer, implementing reference
counitng. I'm using this class for quite a while but have new
enocuntered a nasty little problem:

After I've created a reference counted Object like this

CRefPtr<A> ptr(new A());

I want to use something implement like this at a completely differend
place in my code

CRefPtr<A> A::getSelf();

This is a problem, as the "A" Object does not know ptr (as it's never
submitted). Thus the only way to return a CRefPtr<A> in this case would
be

return CRefPtr<A>(this);

which would lead to ANOTHER Reference counted object, meaning if ptr is
destroyed but there's still an object created by getSelf() around I get
an access violation. Example:

CRefPtr<A> ptr(new A()); // new
CRefPtr<A> ptr2 = ptr->getSelf(); // new, NOT copy
// consider ptr is now destroyed somehow
ptr2->getMember(); // boom, object does not exist but ptr2 still has ref=1

The only possible solution I found is creating a "self" pointer in each
object and assigning it each time I create a new CRefPtr. So I created
an Interface like

template <class T> CRefPtrInterface() {
public:
CRefPtr<T> self;
// ...
};

where self is set with each constructor call from CRefPtr. The Function
getSelf() would just return self. Now there's something not "nice" with
this solution:

class A : public CRefPtrInterface<A> { ... };
class B : public A { ... };

The latter would have self as CRefPtr<A> not CRefPtr<B> as it would be usefull.
Now (finally :) my question: Is it possible to get a CRefPtr<B> self in
class B without overloading it "by hand" in each derived class? Would
something like this work?

class B : public A, public CRefPtrInterface<B> { ... };

Thanks
Arne
 
P

Pete Becker

Arne said:
CRefPtr<A> A::getSelf();

This is a problem, as the "A" Object does not know ptr (as it's never
submitted). Thus the only way to return a CRefPtr<A> in this case would be

return CRefPtr<A>(this);

which would lead to ANOTHER Reference counted object, meaning if ptr is
destroyed but there's still an object created by getSelf() around I get
an access violation.

Read about enable_shared_from_this in TR1:
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2005/n1745.pdf
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,777
Messages
2,569,604
Members
45,230
Latest member
LifeBoostCBD

Latest Threads

Top