Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is auto_ptr deprecated?

  1. Will auto_ptr be deprecated in incoming C++ standard?
  2. Should unique_ptr be used for ownership transfer instead of shared_ptr?
  3. If unique_ptr is not in the standard, then do I need to use shared_ptr instead?
like image 216
dimba Avatar asked Mar 08 '10 19:03

dimba


People also ask

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.

Why auto_ptr Cannot be used with STL?

The C++ Standard says that an STL element must be "copy-constructible" and "assignable." In other words, an element must be able to be assigned or copied and the two elements are logically independent. std::auto_ptr does not fulfill this requirement.

Are smart pointers deprecated?

The standard committee decided that pointers will be deprecated in C++20 and will with very high probability be removed in C++23. To be honest, what seems like a revolution is only the last step in a long evolution.

Why would you choose shared_ptr instead of unique_ptr?

In short: Use unique_ptr when you want a single pointer to an object that will be reclaimed when that single pointer is destroyed. Use shared_ptr when you want multiple pointers to the same resource.


2 Answers

UPDATE: This answer was written in 2010 and as anticipated std::auto_ptr has been deprecated. The advice is entirely valid.

In C++0x std::auto_ptr will be deprecated in favor of std::unique_ptr. The choice of smart pointer will depend on your use case and your requirements, with std::unique_ptr with move semantics for single ownership that can be used inside containers (using move semantics) and std::shared_ptr when ownership is shared.

You should try to use the smart pointer that best fits the situation, choosing the correct pointer type provides other programmers with insight into your design.

like image 52
David Rodríguez - dribeas Avatar answered Sep 24 '22 19:09

David Rodríguez - dribeas


Yes, as of today auto_ptr will be deprecated in C++0x and you should use unique_ptr instead. From the latest draft standard (n3035), section D.9

The class template auto_ptr is deprecated. [ Note: The class template unique_ptr (20.9.10) provides a better solution. —end note ]

Until the standard is ratified, it's always possible that the committee will revise this decision although I feel that is unlikely for this decision.

like image 25
R Samuel Klatchko Avatar answered Sep 22 '22 19:09

R Samuel Klatchko