The Title pretty much sums up my question. Why can't the following be done to check for a null pointer?
auto_ptr<char> p( some_expression );
// ...
if ( !p ) // error
This must be done instead:
if ( !p.get() ) // OK
Why doesn't auto_ptr<T>
simply have operator!()
defined?
Seems to be there was an error in its design. This will be fixed in C++0x. unique_ptr
(replacement for auto_ptr
) contains explicit operator bool() const;
Quote from new C++ Standard:
The class template auto_ptr is deprecated. [Note: The class template unique_ptr (20.9.10) provides a better solution. —end note ]
Some clarification:
Q: What's wrong with a.get() == 0
?
A: Nothing is wrong with a.get()==0
, but smart pointers lets you work with them as they were real pointers. Additional operator bool()
gives you such a choice. I think, that the real reason for making auto_ptr
deprecated is that is has has not intuitive design. But operator bool
for unique_ptr
in the new Standard means that there are no reasons not to have it.