Wednesday, 26 August 2009

auto_ptr with arrays - and a solution

It is pretty irritating that auto_ptr (a feature of C++, for those who don't know!) doesn't work with array variables.

In other words, it is not safe to do this:


int *pArray = new int[10];
auto_ptr autodel(pArray);


It is pretty easy however to create your own alternative to auto_ptr, that works with array pointers...

template <class T> class auto_ptr_array
{
public:
auto_ptr_array(T *p) :
mp(p)
{
}

~auto_ptr_array()
{
delete[] mp;
}

void reset(T *p)
{
delete []mp;
mp = p;
}

T *get()
{
return mp;
}

T* release()
{
T* lpRet = mp;
mp = NULL;
return lpRet;
}

private:
T *mp;
};


Example usage...

int main (int argc, char *argv[])
{
// Use it one of two ways...
auto_ptr_array autodel(new int[20]);
int *pval = autodel.get();

int *pval2 = new int[20];
auto_ptr_array autodel2(pval2);

printf ("Done!\n");

return 0;
}

No comments: