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 <memory>

void memory_leak(){

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

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

std::auto_ptr<int> p;  // constructor 

std::auto_ptr<int> p2;  // constructor

p = std::auto_ptr<int>(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

 

 

 

 

posted @ 2020-01-20 22:15  心怀阳光  阅读(311)  评论(0编辑  收藏  举报