...

/

Removing auto_ptr

Removing auto_ptr

The lesson introduces how the pointers have been revamped for the better.

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:

Press + to interact
#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 ...