If I want to load an object from a file, there are a number of things that can go wrong. Thus, one needs a way of handling errors when doing so. In some languages, like haskell, one can return a Maybe
object that might contain the newly created object. In C++
, although it is in principle possible to create such a convenience class, it is usually not the most straight-forward way to do things. Below I list various ways errors could be handled when loading an object from a file in C++
.
- Return a pointer:
Object* load_from_file(const char* filename);
By returning a pointer, we can return nullptr
in case a problem occured while loading the object.
- Take a reference to a default constructed object and return
false
if a problem occured:
bool load_from_file(const char* filename, Object& obj);
Using this method, a separate initialization method needs to be implemented for the object, which will be called after loading it from the file.
- Throw an exception inside the
load_from_file
function:
Object load_from_file(const char* filename);
Generally, I believe, throwing an exception in such a case might be bad, as this is not really an "exceptional" case.
- Load data to an intermediate
struct
:
struct ObjectData{
//data
};
bool load_from_file(const char* filename, ObjectData& data);
//example use:
ObjectData data;
if(load_from_file("path_to_some_file", data)){
Object(data);
//etc...
}
The difference here with the second method is that you do not need to create an initialization method for Object
.
Generally, what is the preferred method for the problem described above, or which method is preferred in which cases?
nullptr
return value.optional
in the C++ world. boost has a battle-tested implementation and Library TS1 has it, with the hope that it will be in C++17