Monday, January 01, 2007

Usage of auto_ptr, and about Proxy Class technique

This example is incorrect

auto_ptr <char>pChar;
pChar.reset(new char[20]);

In fact, the standard version of auto_ptr can not handle the pointer with array, because when the auto_ptr destructed, it express "delete something" rather then "delete[] something". I think anyone who slightly understand what different of delete and delete[] will point out it will cause memory leak. But how can we enjoy the convenience of auto_ptr, and use array correctly?

There is a trick(technique?) called "proxy class technique". What proxy class stand for? If we need to operate on something, but the operation is not compatible on this, we can make a class to "warp up" this object, and make it compatible to the operation. For example, since auto_ptr is not suitable for a pointer with array, why not we just wrap this pointer up?

struct proxychar
{
char* target; //this is the object.
proxychar(int n){target = new char[n];}
~proxychar(){delete[] target;}
};

auto_ptr<proxychar> pPC;
pPC.reset(new proxychar(20) );

pPC->target[0] = 'H';
pPC->target[1] = 'i';
pPC->target[2] = '\0';
cout << pPC->target;

Ok, it seems working fine. When pPC is being destroyed, it will call up the destructor of proxychar, and it will delete[] target.

This is a application of proxy class technique, and this technique have other use. In this case, this trick plays well =').