仅当满足其构造函数中的某些条件时,我才想创建结构的实例。如果不满足这些条件,我不想创建实例。不确定这是否可能,如果不是,那么另一种方法是什么?
Class Consumer
{
struct SampleStruct
{
MyClass * m_object;
RoutingItem()
{
m_object = NULL;
}
MyClass(std::string name)
{
if (! ObjSetting()->GetObj(name, m_object))//this function is supposed to populate m_object, but if it fails, I dont want to create this instance
return; //I dont want to create this object if GetObj() returns a false
}
};
std::vector<SampleStruct> m_arrSample;
void LoadSettings(std::string name)
{
SampleStruct * ptrS;
SampleStruct s(name);
//I tried following two lines but it did'nt work. SO looks like returning from struct constructor still creates the instance
ptrS = &s;
if (!ptrS)
return;
m_arrSample.push_back(s);//only insert in vector if sampleStruct was successfully created
}
}