I’d like to have a simple way of checking for an object to be valid. I thought of a simple conversion function, something like this:
operator bool() const { return is_valid; }
Checking for it to be valid would be very simple now
// is my object invalid?
if (!my_object) std::cerr << "my_object isn't valid" << std::endl;
Is this considered a good practise?
In C++03, you need to use the safe bool idiom to avoid evil things:
In C++11 you can use an explicit conversion:
This way you need to be explicit about the conversion to bool, so you can no longer do crazy things by accident (in C++ you can always do crazy things on purpose):
This still works as normal in places like
ifandwhilethat require a boolean expression, because the condition of those statements is contextually converted to bool:This is documented in §4[conv]:
(What makes the difference is the use of
bool t(e);instead ofbool t = e;.)The places were this contextual conversion to bool happens are:
if,while, andforstatements;!, logical conjunction&&, and logical disjunction||;?:;static_assert;noexceptexception specifier;