I’m doing some work in C++, and I had a code review today. The following discussion occurred:

Reviewer 1
Why do you always create objects using “new” instead of just on the stack?
Me
I don’t like to abuse the stack. I’ve worked in too many environments where stack overflows were a major source of pain.
Reviewer 2
You could use an auto_ptr.

At this point the conversation moved on, which was a great relief because I had no idea what an auto_ptr is. The last time I used C++ was when many things that are now part of the idiom didn’t exist at all, or didn’t exist for kernel programmers, or couldn’t be trusted; STL, namespaces, and even templates all fit into this category.

So I looked it up. All I can say is: yech. I’ve never liked operator overloading in any form, and “smart pointers” in particular, and IMO auto_ptr is an example of why they’re a bad idea – not of how they can be used safely. Consider this, from a pro auto_ptr article:

I have seen many programmers try to use auto_ptrs in other ways just as they would use any other object. The problem with this is that auto_ptrs are most assuredly not like any other object.

For auto_ptr, copies are NOT equivalent.
It turns out that this has important effects when you try to use auto_ptrs with generic code that does make copies and isn’t necessarily aware that copies aren’t equivalent (after all, usually copies are!).

It is never safe to put auto_ptrs into standard containers.

Again, yech. Those are some serious differences between an auto_ptr and a regular pointer (which it is supposed to replace transparently). The author even admits that many programmers have had problems because they weren’t aware of the differences, but doesn’t draw the obvious conclusion that replacing one faulty abstraction (regular pointers and memory leaks) with another (auto pointers and “spooky” bugs resulting from their unexpected behavior) is dumb.

In conclusion, I can’t help but quote from the article’s acknowledgments. The very fact that a book with such a title even exists could be considered evidence that C++ rots your brain.

This article is drawn from material in the new book Exceptional C++: 47 engineering puzzles, programming problems, and exception-safety solutions