c++, auto_pointer

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.

1. auto pointer

扫描二维码关注公众号,回复: 8739221 查看本文章

#include <memory>

void memory_leak(){

  std::auto_ptr<ClassA> ptr(new ClassA);

   // delete ptr is not needed

}

2. Several things on auto_ptr

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; 

std::auto_ptr<int> p2;

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

*p = 11;  //ok

p2 = p;  //ok

auto_ptr is deprecated in  c++11 and removed in c++17.

 

 

猜你喜欢

转载自www.cnblogs.com/sarah-zhang/p/12217194.html