On 2002-06-06, Nadav Har'El wrote:
> On Thu, Jun 06, 2002, Christoph Bugel wrote about "Re: Some C++ Questions":
> > > And never do something like "delete this"!
> > 
> > I guess "never" is not the correct word.
> > There *are* legitimate uses of "delete this",
> > For example in the RCProxy design pattern.
> 
> I'm not a design-patterns expert, so maybe I'm missing something, but
> how can you do "delete this" from within an object? First, I don't see
> how you know that this object was dynamically-allocated (it might have
> been on the stack, allocated as part of an array of objects, allocated
> with placement-new, etc.).
> 
> Second, what happens after the "delete this"? The method continues to
> run but the object was destructed; If you do anything except "return"
> after the "delete this" you might accidentally try to use members of
> the deleted object...

I'm by no means a design patterns expert either :-)

But I'll try to explain the Reference-Counted Proxy pattern, as I
understand it: There is a class that is for the user (the proxy class)
and another class that contains the actual implementation, which should
never be used directly by the user. For example, class String and class
StringImp. The user creates objects of type String, and doesn't even know
about the implementation class.

when you create a String (String s1("foo");), the constructor does 
_imp = new StringImp("foo") --  on the heap --  and then calls
_imp->IncrementReferenceCount() 
*All* things you subsequently do with the string, are delegated to the
_imp.  for example String.Append(a) calls _imp->Append(a) So basically
the String class is just a proxy, and doesn't know anything about real
Strings.

When you make copies of that String: String s2 = s1;

The copy constructor doesn't create another *new* string, but uses the
same StringImp of s1, and then calls _imp->IncrementReferenceCount() This
is the reason for this pattern, useful if the implementation object is
expensive, and may be shared by various users.
(In case of strings this is true, as long as the strings are constant)

the Destructor of String (for example, when your s1 goes out of scope on
the stack) simply calls _imp->DecrementReferenceCount()

assuming your s2 is still on the stack, the reference count is now 1;
when your s2 goes out of scope too, the _imp->DecrementReferenceCount()
is called again.

DecrementReferenceCount always checks:
if _refcount == 0 delete this;

So the Implementation class know that no one is using it anymore, and it
can be safely deleted. and after delete thisd, the function exits, and
nonoe ever uses that object again. (how sad :-)

I hope this made a little sense

Christoph





=================================================================
To unsubscribe, send mail to [EMAIL PROTECTED] with
the word "unsubscribe" in the message body, e.g., run the command
echo unsubscribe | mail [EMAIL PROTECTED]

Reply via email to