Never Create Containers of auto_ptrs
21 Mar 2017One more item I read from effective STL last evening was about containers of auto_ptr. I was just looking to know more about auto_ptr. I haven’t used auto_ptr before. And I am glad I read this item before I could use auto_ptr.
When you assign an auto_ptr to another auto_ptr, the source auto_ptr becomes null. That seems like a nasty ptr type.
So, if you have a container of auto_ptr objects and if the container goes through some algorithm that temporarily stores value(s) from the container in some variable(s), you are going to lose those values. An example algorithm, as demonstrated in the item would be quick sort which stores values for pivot elements.
Let’s write some code and see things go wrong with a container of auto_ptr objects.
-
It took a while.
The first problem I hit was that it’s impossible to create a vector of auto_ptr objects. auto_ptr constructor takes a mutable reference. Whereas vector::push_back takes a const reference and then tries to create a new auto_ptr object from it, which is impossible.
After some struggle with iterators, auto_ptr, array references, comparison functions and pointers, I had working code to display the horror of auto_ptr.
The code demonstrates 3 different ways of sorting:
- sorting a shared_ptr array using std::sort
- sorting an auto_ptr array using qsort
- sorting an auto_ptr array using std::sort
While #1 and #2, succeed, #3 fails with seg fault. Thus, proving that auto_ptr containers are a bad idea.
-
Code:
Output:
unsorted:
83 86 77 15 93 35 86 92 49 21 62 27 90 59 63 26 40 26 72 36 11 68 67 29 82 30 62 23 67 35
sorted shared_ptr array using std::sort:
11 15 21 23 26 26 27 29 30 35 35 36 40 49 59 62 62 63 67 67 68 72 77 82 83 86 86 90 92 93
sorted auto_ptr array using qsort:
11 15 21 23 26 26 27 29 30 35 35 36 40 49 59 62 62 63 67 67 68 72 77 82 83 86 86 90 92 93
sorted auto_ptr array using std::sort:
Segmentation fault (core dumped)
-
The code needs to be compiled with: -std=C++11 (for std::begin and std::end) -w (to ignore auto_ptr deprecation warnings)
-