I have member function that looks like:
Point find_the_special_point(Image img);
However, this function may fail to find the point (for example the img
does not contain a special point at all).
What is the right way to make the function return in some way that the point was not found?
I thought of some solutions but not sure which one the best or if there is a better approach:
1. Throwing exception if the point is not found:
I think it is just stupid because exceptions are not mean to control the flow. Furthermore, not finding a point is an expected behavior not an exception.
2. Alter the declaration to:
Bool find_the_special_point(Image img , Point& pnt);
Although it seems correct way, I think (not sure) that it is not so good to return the actual output via arguments.
3. Wrapping the out put:
struct find_the_special_point_result{
bool is found;
Point special_point;
};
find_the_special_point_result find_the_special_point(Image img);
It seems to be nice solution. However, I suspect that it is a bit overkill.
4. Returning pointer instead:
std::shared_ptr<Point> find_the_special_point(Image img);
and if it is not found return nullptr
. However, I think dynamic allocation was not made for this case. It is kind of using the wrong tool to achieve another goal.
What is the convention way to solve this issue?
std::map::insert
does (the struct isstd::pair<iterator, bool>
), orstd::optional<Point>
if you have a C++17 compiler – Caleth Feb 23 '18 at 13:47Image
always have a special point? If it should, then throwing an exception is fine. – Vincent Savard Feb 23 '18 at 13:58