删除删除/删除[]

jav*_*rda 1 c++ memory-management smart-pointers raii visual-c++

我正在尝试删除旧应用程序的所有删除和删除[],而是使用智能指针.在下面的代码片段中,我想删除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;
}
Run Code Online (Sandbox Code Playgroud)

您认为这种情况的最佳方法是什么:使用包装器对象来跟踪所有创建的数组并在析构函数中删除它们或使用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]));
}
Run Code Online (Sandbox Code Playgroud)

我需要使用boost :: shared_ptr,因为我使用的是VC++ 2008

提前致谢.J.拉塞尔达

Mat*_*lia 10

std::vector<std::string > objs(numFiles, std::string(MAX_PATH, 0));
std::vector<MapiFileDesc> fileDesc(numFiles);
for (int i = 0; i < numFiles; ++i)
    fileDesc[i].lpszPathName=objs[i].data();
// after the C API calls, if you do need to use the strings as C++ strings,
// resync the C++ string length with the C string data
// (not necessary if you just use them via c_str())
for (int i = 0; i < numFiles; ++i)
    objs[i].resize(strlen(objs[i].c_str());
Run Code Online (Sandbox Code Playgroud)

顺便说一句,如果你不需要将整个数组传递给C API而只需要传递单个结构,你可以创建一个结构的单个向量来存储MapiFileDesc结构和std::string两个对象的生命周期,并允许构造函数来处理lpszPathName与字符串data()成员的链接; 仍然,如果这个结构只用在一个函数中,我可能不会打扰.