Deleting an object if the constructor failed.
Hi guys, I want to ask you about how to delete an object if its constructor failed to initialize one of its members. I tried it like below but failed:
Code:
B* A:CreateB(std::string paramStr)
{
B* pB= NULL;
try
{
pB = new pB (paramStr);
}
catch (int result)
{
if (result == OK) // OK == 1
{
m_VectorB.push_back(pB);
}
else if (result == FAILED)
{
delete pB;
pB = NULL;
}
}
return pB;
}
B::B(std::string paramStr)
{
int result = initMembers (paramStr); //returns OK / 1 if successful or FAILED / 0 if failed
throw result ;
}
Now, FYI, I have never ever ever used exception in my entire life as a programmer. All my error handlings are either by return value or assertion. I know that it is not a good habit but I still don't have a good understanding about it. So, how can I solve this problem? Thanks in advance.