Boost logo

Boost Users :

Subject: [Boost-users] [optional] Comparing boost::optional<T> to NULL yield inconsistent results
From: Martin B. (0xCDCDCDCD_at_[hidden])
Date: 2011-04-12 09:57:38


Hi.

I have the following problem: One of our devs used (my_opt != NULL) to
check an boost::optional for emptiness.

This lead me to write the following test case:

...
using namespace std;
boost::optional<int> num_opt;
boost::optional< std::string > obj_opt;

if(obj_opt) {
   cout << "(3) Object: " << *obj_opt << endl;
}

// Compiles and does what the user intended -
// BUT is this what the boost optional interface intends?? -
// namely checking the optional for empty:
if(obj_opt != NULL) {
   cout << "(4) Object: " << *obj_opt << endl;
}

if(num_opt) {
   cout << "(1) Integer: " << *num_opt << endl;
}

// Compiles and crashes, because the user actually
// should have written if(num_opt) but, being used to pointers,
// wrote the below, which compiles fine, but does not check for empty
// but for equality with zero:
if(num_opt != NULL) {
   cout << "(2) Integer: " << *num_opt << endl;
}
...

I find the behaviour of boost::optional<int> vs. opt<ClassType> highly
un-intuitive.

Wouldn't it be better if comparing an boost::optional always required to
"dereference" it?

I checked the headers (Boost 1.44) and sadly there doen't seem to be a
preprocessor switch to disable the implicit comparison operators ...

I would appreciate if other users could comment on my observations. Thanks!

cheers,
Martin


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net