码迷,mamicode.com
首页 > 编程语言 > 详细

c++, auto_pointer

时间:2020-01-20 22:46:08      阅读:94      评论:0      收藏:0      [点我收藏+]

标签:The   point   size   mes   moved   erro   data   use   sel   

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

标签:The   point   size   mes   moved   erro   data   use   sel   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!