In a library I have a function which searches for a key in a database and return a non-const reference to an object. I want to handle the case in which the key is not found, which is typically caused by a mistake when calling the function. This situation is so bad that the program cannot continue, so I print a message to help to spot the bug and call exit(1)
. The problem is with the return statement which will never be executed in this case, but have to be there anyway. If it was a pointer I could just return nullptr;
but with a reference? Should I do something like this pseudo code?
Type & get(const Key & k) {
if (my_db.key_exists(k)) {
return my_db.at(k);
}
std::cerr << k << " not found\n";
exit(1);
return *(new Type(some_dummy_parameters));
}
It looks so awful! Maybe I should just avoid such a function. Please, let me know your opinion!