0. Problem
There is no memory leak of the following code, but there are problems.
void memory_leak(){
ClassA *ptr = new ClassA();
/* if return here, the deleting will not be executed, then memory leak;
* if an exception happens, the deleting will not be executed, then memory leak;
*/
delete ptr;
}
So, we need a pointer that can free the data to which it points whenever the pointer itself gets destroyed.
#include
void memory_leak(){
std::auto_ptr
// delete ptr is not needed
}
1. auto pointer
auto_ptr is a smart pointer that manages an object obtained via new expression and deletes that object when auto_ptr itself is destroyed.
copying an auto_ptr copies the pointer and transfers ownership to the destination.
3. Examples
4. Several things on auto_ptr
auto_ptr is deprecated in c++11 and removed in c++17
ptr++; // error, no definition of ++ operator
std::auto_ptr
std::auto_ptr
std::auto_ptr
std::auto_ptr
p = std::auto_ptr
*p = 11; //ok
p2 = p; // =operator, ownership transfers
p2.get(); // ok
p.get(); // ok, p is nullptr, becasue the ownership has been transfered