Auto pointer for unsigned char array?
Posted
by Gianluca
on Stack Overflow
See other posts from Stack Overflow
or by Gianluca
Published on 2010-04-26T12:49:24Z
Indexed on
2010/04/26
12:53 UTC
Read the original article
Hit count: 218
c++
I'd need a class like std::auto_ptr for an array of unsigned char*, allocated with new[]. But auto_ptr only calls delete and not delete[], so i can't use it.
I also need to have a function which creates and returns the array. I came out with my own implementation within a class ArrayDeleter, which i use like in this example:
#include <Utils/ArrayDeleter.hxx>
typedef Utils::ArrayDeleter<unsigned char> Bytes;
void f()
{
// Create array with new
unsigned char* xBytes = new unsigned char[10];
// pass array to constructor of ArrayDeleter and
// wrap it into auto_ptr
return std::auto_ptr<Bytes>(new Bytes(xBytes));
}
...
// usage of return value
{
auto_ptr<Bytes> xBytes(f());
}// unsigned char* is destroyed with delete[] in destructor of ArrayDeleter
Is there a more elegant way to solve this? (Even using another "popular" library)
© Stack Overflow or respective owner