我需要一個像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
有沒有辦法解決這個問題一個更優雅的方式? (即使使用另一個「流行」庫)
我看了一下boost,我認爲scoped_array會這樣做。謝謝 – Gianluca 2010-04-26 13:04:34
@Gianluca:你爲什麼不使用矢量? – GManNickG 2010-04-26 14:32:38
@GMan:當然,現在我看到這是一個更好的主意。謝謝 – Gianluca 2010-04-26 15:02:00