Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't auto_ptr<T> have operator!() defined?

Tags:

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?

like image 815
Paul J. Lucas Avatar asked Jun 30 '10 16:06

Paul J. Lucas


People also ask

Why was auto_ptr removed?

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 auto_ptr is deprecated?

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.

Is auto_ptr deprecated?

The C++11 standard made auto_ptr deprecated, replacing it with the unique_ptr class template. auto_ptr was fully removed in C++17.

How is auto_ptr implemented?

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.


1 Answers

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.

like image 71
Kirill V. Lyadvinsky Avatar answered Sep 24 '22 01:09

Kirill V. Lyadvinsky