Legacy C++ › 7. Idioms and Patterns
std::auto_ptr
The C++98 smart pointer: single ownership via copy-that-moves, and the pitfalls that led to its replacement.
Since C++98 Removed in C++17 intermediate #smart-pointers#auto_ptr#ownership
Explanation
std::auto_ptr<T> (header <memory>) is a C++98 RAII wrapper that calls delete on its pointee when destroyed. It models exclusive ownership, implemented by making copying transfer ownership: after a = b, b holds a null pointer.
It was deprecated in C++11 and removed in C++17. This page covers how it behaved so you can read and migrate old code.
Example
Compile with -std=c++03 (or c++14 with a deprecation warning).
#include <iostream>
#include <memory>
struct Widget {
Widget() { std::cout << "Widget created\n"; }
~Widget() { std::cout << "Widget destroyed\n"; }
void hello() const { std::cout << "hello\n"; }
};
std::auto_ptr<Widget> make() { return std::auto_ptr<Widget>(new Widget); }
int main() {
std::auto_ptr<Widget> a = make();
a->hello();
std::auto_ptr<Widget> b = a; // ownership MOVES to b
std::cout << (a.get() == 0 ? "a is null\n" : "a still owns\n");
b->hello();
return 0; // Widget destroyed exactly once
}
Pitfalls
- Copy is not a copy. Passing an
auto_ptrby value to a function silently empties the caller’s pointer. - Unusable in STL containers.
std::vector<std::auto_ptr<T>>requires copyable elements with copy semantics; algorithms such asstd::sortmay copy elements around and null them out. - No arrays. It calls
delete, neverdelete[]. - No custom deleters, so it cannot manage files, handles, or
malloced memory.
Legacy vs modern
| Need | C++98 | C++11 and later |
|---|---|---|
| Exclusive ownership | auto_ptr |
std::unique_ptr (move-only, container-safe, arrays, deleters) |
| Shared ownership | hand-rolled or Boost shared_ptr |
std::shared_ptr |
unique_ptr makes the ownership transfer explicit with std::move, so the compiler rejects accidental copies. See Move Semantics and unique_ptr.
Exercises
1. What does a contain after std::auto_ptr<int> b(a);?
A null pointer. Ownership moved to b.