Search⌘ K

Removing auto_ptr

Understand why auto_ptr was removed in C++17 due to its unsafe behavior and lack of move semantics. Learn how to replace auto_ptr with modern smart pointers such as unique_ptr and shared_ptr, which offer safer and clearer ownership models. Discover practical coding examples and tips to avoid common runtime errors and manage resource ownership correctly in modern C++.

We'll cover the following...

​C++98 added auto_ptr as a way to support basic RAII features for raw pointers. However, due to the lack of move semantics in the language, this smart pointer could be easily misused and cause runtime errors.

Here’s an example where auto_ptr might cause a crash:

C++
#include <iostream>
#include <memory>
void doSomething(std::auto_ptr<int> myPtr)
{
*myPtr = 11;
std::cout << *myPtr;
}
void AutoPtrTest() {
std::auto_ptr<int> myTest(new int(10));
std::cout << *myTest;
doSomething(myTest);
*myTest = 12;
std::cout << *myTest;
}
int main(){
AutoPtrTest();
}

doSomething() takes auto_ptr by value, but since it’s not a shared pointer, it gets the unique ownership of the managed object. Later, when the function is completed, the copy of the pointer goes out of scope, and the object is deleted.

In AutoPtrTest() when ...