我想刪除舊的應用程序的所有刪除和刪除[],並使用智能指針。在下面的代碼片段中,我想刪除最後一個cicle。刪除刪除/刪除[]
std::unique_ptr<MapiFileDesc> fileDesc(new MapiFileDesc[numFiles]);
for (int i = 0; i < numFiles; ++i)
{
// Works but I've to delete[] at the end
fileDesc[i].lpszPathName = new CHAR[MAX_PATH];
// Does not work. For each iteration the previous array will be deleted
// It also happens with shared_array
boost::scoped_array<CHAR> pathName(new CHAR[MAX_PATH]);
fileDesc[i].lpszPathName = pathName.get();
}
// I want to remove the following cicle
for (int i = 0; i < numFiles; ++i)
{
delete [] fileDesc[i].lpszPathName;
fileDesc[i].lpszPathName = nullptr;
}
你認爲它是造成這種情況的最佳方法:使用包裝對象,將跟蹤創建的所有陣列,並在析構函數刪除或使用boost :: shared_array的載體和分配他們對每個元素?
std::vector<boost::shared_array<CHAR> > objs;
for (int i = 0; i < 10; ++i)
{
objs.push_back(boost::shared_array<CHAR>(new CHAR[MAX_PATH]));
}
我需要的,因爲我使用VC++ 2008
在此先感謝使用boost :: shared_ptr的。 J.拉塞爾達
使用'std :: string'。 – Fanael
如果您使用'new []'進行分配,則需要'std :: unique_ptr'。但是,使用'std:string'代替。 –
juanchopanza
@juanchopanza只是爲了好奇,這是C++ 11的唯一語法,還是它可以和(舊的)std :: auto_ptr一起正常工作呢? –