我创建了一个类,如果其中一个成员为空,我不想创建对象。以下是代码行:
#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();
}
这样可以吗?还是我需要做更多的事情?如果抛出异常,我如何确保对象不会被创建?
我有以下代码行来确保它:
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;
}
}
b2
是被初始化的。和所有成员一样,在构造函数体开始之前就已经被初始化了。当构造函数抛出异常时,部分构造的对象的成员将会被销毁(删除由b1
拥有的对象,并对空的b2
不做任何操作),并且一旦控制流程到达异常处理程序,该对象本身将无法访问。 - Mike Seymour