zoukankan      html  css  js  c++  java
  • 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

     

     

  • 相关阅读:
    Java实现八大排序算法
    Java实现二分查找算法
    Win10下通过IIS调试ASP程序遇到的问题和解决方案
    Nginx几种负载均衡算法及配置实例
    Java解决CSRF问题
    Nginx Https配置不带www跳转www
    面试中的Https
    面试中的DNS
    java系列视频教程下载
    关于Mysql DATE_FORMAT() 日期格式
  • 原文地址:https://www.cnblogs.com/sarah-zhang/p/12217194.html
Copyright © 2011-2022 走看看