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?
Since the assignment-semantics was most-disliked feature, they wanted that feature to go away, but since there is code written that uses that semantics, (which standards-committee can not change), they had to let go of auto_ptr, instead of modifying it.
Why is auto_ptr deprecated? It takes ownership of the pointer in a way that no two pointers should contain the same object. Assignment transfers ownership and resets the rvalue auto pointer to a null pointer. Thus, they can't be used within STL containers due to the aforementioned inability to be copied.
The C++11 standard made auto_ptr deprecated, replacing it with the unique_ptr class template. auto_ptr was fully removed in C++17.
The auto_ptr transfers the ownership of internal resource during a copy operation. Furthermore, such a behavior happens in both the cases of copy. That is whenever a new auto_ptr is constructed using copy constructor or whenever an assignment operation happens.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With