我正在尝试删除旧应用程序的所有 delete 和 delete[] 并改用智能指针。在下面的代码片段中,我想删除 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]));
}
我需要使用 boost::shared_ptr 因为我使用的是 VC++ 2008
提前致谢。J.拉塞尔达