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:
Post a Comment