无符号字符数组的自动指针?

Gia*_*uca 3 c++

我需要一个像std :: auto_ptr这样的类来表示一个unsigned char*数组,用new []分配.但是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
Run Code Online (Sandbox Code Playgroud)

有更优雅的方法来解决这个问题吗?(即使使用另一个"流行"图书馆)

Joh*_*don 11

Boost有各种自动指针,包括数组.你有没有考虑过std :: vector是否足够?保证向量在内存中是连续的,如果您提前知道大小和分配的内存,则内存中的位置不会更改.

  • @Gianluca:你为什么不用矢量? (3认同)