Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is auto_ptr being deprecated?

I heard auto_ptr is being deprecated in C++11. What is the reason for this?

Also I would like to know the difference between auto_ptr and shared_ptr.

like image 315
brett Avatar asked Sep 13 '10 03:09

brett


People also ask

Why is auto_ptr 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.

When was 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.

Why auto_ptr Cannot be used with STL?

Since objects within an STL container must be copy-constructible and assignable, a compile time error is provided if an auto_ptr is used within a container. Algorithms, such as those involved in sorting STL containers, often copy objects while carrying out their tasks.

What is the difference between auto_ptr and unique_ptr?

As for other differences, unique_ptr can handle arrays correctly (it will call delete[] , while auto_ptr will attempt to call delete .


1 Answers

The direct replacement for auto_ptr (or the closest thing to one anyway) is unique_ptr. As far as the "problem" goes, it's pretty simple: auto_ptr transfers ownership when it's assigned. unique_ptr also transfers ownership, but thanks to codification of move semantics and the magic of rvalue references, it can do so considerably more naturally. It also "fits" with the rest of the standard library considerably better (though, in fairness, some of that is thanks to the rest of the library changing to accommodate move semantics instead of always requiring copying).

The change in name is also (IMO) a welcome one -- auto_ptr doesn't really tell you much about what it attempts to automate, whereas unique_ptr is a fairly reasonable (if terse) description of what's provided.

like image 129
Jerry Coffin Avatar answered Sep 22 '22 01:09

Jerry Coffin