我需要一个类似于std::auto_ptr的类来管理一个使用new[]分配的unsigned char*数组。但是auto_ptr只会调用delete而不是delete[],所以我不能使用它。
我还需要一个函数来创建并返回该数组。我自己实现了一个名为ArrayDeleter的类,在这个例子中我使用它:
#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
有没有更优雅的解决方法?(甚至使用另一个“流行”的库)