c++, std::auto_ptr

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 ptr(new ClassA);

   // 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 ptr1(new ClassA); // ok

std::auto_ptr ptr2 = new ClassA ; // error because assignment syntax

std::auto_ptr p;  // constructor 

std::auto_ptr p2;  // constructor

p = std::auto_ptr(new int); //ok

*p = 11;  //ok

p2 = p;  // =operator, ownership transfers

p2.get(); // ok

p.get(); // ok, p is nullptr, becasue the ownership has been transfered

 

 

 

 

你可能感兴趣的:(c++, std::auto_ptr)