Presenting the Problem
Suppose you're designing a smart pointer class. In addition to overloading the operators
* and
->, a smart pointer class usually defines a
conversion operator to
bool:
template <class T>
class Ptr
{
public:
operator bool() const
{
return (rawptr ? true: false);
}
//..more stuff
private:
T * rawptr;
};
The conversion to
bool enables clients to use smart pointers in expressions that require
bool operands:
Ptr<int> ptr(new int);
if(ptr ) //calls operator bool()
cout<<"int value is: "<<*ptr <<endl;
else
cout<<"empty"<<endl;
Furthermore, the implicit conversion to
bool is required in conditional declarations such as:
if (shared_ptr<X> px = dynamic_pointer_cast<X>(py))
{
//we get here only of px isn't empty
}
Alas, this automatic conversion opens the gate to unwelcome surprises:
Ptr <int> p1;
Ptr <double> p2;
//surprise #1
cout<<"p1 + p2 = "<< p1+p2 <<endl; //prints 0, 1, or 2
Ptr <File> pf;
Ptr <Query> pq; // Query and File are unrelated
//surprise #2
if(pf==pq) //compares bool values, not pointers!