std::auto_ptr
was a pre-C++11 attempt to do what std::unique_ptr
now does. Unfortunately, the move semantics needed to
make it work properly weren’t in place, so copying a std::auto_ptr
has the very surprising behavior of invalidating the source of the
copy.
That problem has been fixed with std::unique_ptr
, so std::auto_ptr
has been deprecated in C++11 and removed in C++17.
If your compiler allows it, you should replace all use of std::auto_ptr
with std::unique_ptr
. Otherwise, define your own
(non-copyable) smart pointer.
Noncompliant code example
void draw(std::auto_ptr<Shape> p) { // Noncompliant
std::cout << s->x() << ", " << s.y() << std::endl;
}
void f() {
std::auto_ptr<Shape> s = createShape(); // Noncompliant
draw(s); // This call invalidates s
draw(s); // This call will crash, because s is null
}
Compliant solution
void draw(std::unique_ptr<Shape> p) { // Compliant
std::cout << s->x() << ", " << s.y() << std::endl;
}
void f() {
std::unique_ptr<Shape> s = createShape();
// draw(s); // Would not compile
draw(move(s)); // Will compile, and the user knows s has been invalidated
}