Suppose I have a static method of my class that returns an object of the same type of my class. To create the object for example this method have to parse a string:
class C
{
public:
static C get_obj(const std::string& str)
{
C obj;
// Parse the string and set obj properties
return obj;
}
};
If, when I parse the string, I get an error and the object can’t be constructed as a valid object, have I to throw an exception or what else?
Given that there is a possibility of failure in
get_objthe failure must be reported back to the caller in some manner. This is typically either done byIn this particular case the only output of the method is a
Cinstance. Given that throwing an exception is probably the best option for a method of this signature. The only other choice is to embed the success / failure inside theCobject which you almost certainly don’t want to do.Another way to approach this problem is the
try_parsepattern. Let aboolreturn indicate success / failure and return the constructed object on success through a reference parameter