简体   繁体   English

安全地删除析构函数中的内存

[英]delete memory safely in destructor

I have the following code: 我有以下代码:

CCOLFile *pCOLFile = CCOLManager::getInstance()->parseFile(strCOLPath);
// ...
pCOLFile->unload();
delete pCOLFile;

Memory is allocated by the parseFile() function and stored in a std::vector in the pCOLFile object. 内存由parseFile()函数分配,并存储在pCOLFile对象的std :: vector中。 Can I move my code from the unload() method to the CCOLFile destructor to safely delete the allocated memory? 我可以将代码从unload()方法移至CCOLFile析构函数以安全地删除分配的内存吗?

I'm guessing destructors maybe were even designed for this? 我猜析构函数可能是为此目的而设计的?

The goal is to iterate around a std::vector and use delete on each value. 目标是迭代std :: vector并在每个值上使用delete。

Here's my CCOLFile struct: 这是我的CCOLFile结构:

struct CCOLFile
{
    std::string                     m_strFilePath;
    std::vector<CCOLEntry*>         m_vecEntries;
};

And here's the current unload() method: 这是当前的unload()方法:

void                CCOLFile::unload(void)
{
    for (auto pCOLEntry : m_vecEntries)
    {
        delete pCOLEntry;
    }
    m_vecEntries.clear();
}

If you declare std::vector<std::unique_ptr<CColEntry>> m_vecEntries then you don't need an unload method; 如果声明std::vector<std::unique_ptr<CColEntry>> m_vecEntries则不需要unload方法; instead, in the destructor, just do delete m_vecEntries . 相反,在析构函数中,只需delete m_vecEntries The vector will clear its entries, and because they are unique_ptr 's, they will delete themselves. vector将清除其条目,并且由于它们是unique_ptr ,因此它们将删除自己。

Thus unload() is reduced to one line in the destructor. 因此,在析构函数中将unload()减少为一行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM