在构造函数c ++中抛出异常

sop*_*sop 2 c++

我创建了一个类,如果一个成员为空,我不想创建该对象.这些是代码行:

#include "verification/CVerifObj.hpp"

VerifObj::VerifObj(const fs::path& imgNameIn)
{
    m_image = cv::imread(imgNameIn.string());
    AnalyseCSV csv;
    m_plateContour = csv.getPlateRegion(imgNameIn); // search for the csv file and load the values
    if (m_plateContour.empty()) // throw exception if empty csv
    {
        throw EmptyContourException(imgNameIn.string());
    }
    m_imageName = imgNameIn.string();
}

VerifObj::~VerifObj()
{
    // are these enough for destructor?
    m_image.release();
    m_plateContour.clear();
}
Run Code Online (Sandbox Code Playgroud)

这样可以,还是我会做更多的事情?如果抛出异常,我怎么能确定没有创建对象?

我有以下几行代码来确保它:

for(fs::directory_iterator iter(folderIn); iter != end; ++iter)
{
    if(!fs::is_regular_file(iter->status()))
    {
        continue;
    }
    std::string extension = iter->path().extension().string();
    if(targetExtensions.find(extension) == targetExtensions.end()) 
    { 
        continue;
    }
    try
    {
        VerifObj verifObj(iter->path());
        verifObjVecRet.push_back(verifObj);
    }
    catch (EmptyContourException& ece)
    {
        continue;
    }
    catch (CSVException &csve)
    {
        continue;
    }
}
Run Code Online (Sandbox Code Playgroud)

Mik*_*our 7

希望m_imagem_plateContour(和你班级的任何其他非平凡成员)都是正确设计的RAII类型,使用析构函数来清理他们可能拥有的任何资源.

在这种情况下,你的类根本不需要析构函数,如果构造函数抛出,所有成员都将被自动正确销毁 - 不需要在那里采取任何操作.

但是,析构函数的存在意味着它们可能是邪恶类型,需要在破坏之前手动清理.在那种情况下,修复它们.

如果由于某种原因无法修复它们,那么m_image.release();在投掷之前你需要它.你还需要大量的咖啡供应,因为这样的类会导致长时间的调试会议试图修复内存泄漏.