Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conversion function for error checking considered good?

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?

like image 795
Karl von Moor Avatar asked Jun 05 '11 10:06

Karl von Moor


2 Answers

In C++03, you need to use the safe bool idiom to avoid evil things:

int x = my_object; // this works 

In C++11 you can use an explicit conversion:

explicit operator bool() const {     // verify if valid     return is_valid; } 

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):

int x = my_object; // does not compile because there's no explicit conversion bool y = bool(my_object); // an explicit conversion does the trick 

This still works as normal in places like if and while that require a boolean expression, because the condition of those statements is contextually converted to bool:

// this uses the explicit conversion "implicitly" if (my_object) {     ... } 

This is documented in §4[conv]:

An expression e can be implicitly converted to a type T if and only if the declaration T t=e; is well-formed, for some invented temporary variable t (§8.5). Certain language constructs require that an expression be converted to a Boolean value. An expression e appearing in such a context is said to be contextually converted to bool and is well-formed if and only if the declaration bool t(e); is well-formed, for some invented temporary variable t (§8.5). The effect of either implicit conversion is the same as performing the declaration and initialization and then using the temporary variable as the result of the conversion.

(What makes the difference is the use of bool t(e); instead of bool t = e;.)

The places were this contextual conversion to bool happens are:

  • the conditions of if, while, and for statements;
  • the operators of logical negation !, logical conjunction &&, and logical disjunction ||;
  • the conditional operator ?:;
  • the condition of static_assert;
  • the optional constant expression of the noexcept exception specifier;
like image 72
R. Martinho Fernandes Avatar answered Sep 30 '22 01:09

R. Martinho Fernandes


No, a simple bool conversion operator is not, as you can now make evil comparisions between unrelated types. Generally, yes, a conversion function is a-okay. Just use the right one (safe-bool idiom). I can't explain it any better than the given links.

like image 37
Xeo Avatar answered Sep 30 '22 00:09

Xeo