首页 > 编程语言 > 详细

c++, auto_pointer

时间:2020-01-20 23:34:40      阅读:126      评论:0      收藏:0      [点我收藏+]

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

#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.

 

 

 

c++, auto_pointer

原文:https://www.cnblogs.com/sarah-zhang/p/12217194.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!