zoukankan      html  css  js  c++  java
  • c++基础 使用智能指针

    三个智能指针模板(auto_ptr、unique_ptr和shard_ptr)都定义了类似指针的对象(c++11已将auto_ptr摒弃),可以将new获得(直接或间接)

    的地址赋给这种对象。当智能指针过期时,其析构函数将使用delete来释放内存。因此,如果将new返回的地址赋给

    这些对象,将无需记住稍后释放这些内存:在智能指针过期时,这些内存将自动被释放。

    下图说明了auto_ptr和常规指针在行为方面的差另:share_ptr和unique_ptr的行为与auto_ptr相同

    使用智能指针必须包含头文件memory文件模板定义。然后使用通常的械板语法来实例化所需类型的指针。

    auto_pter包含如下的构造函数

    template<class x> 

    class auto_ptr
    {

    public:

      explicit auto_ptr(X * p=0)throw();

    };

    thro()意味着构造函数不会引发异常;与auto_ptr一样,throw()也被摒弃。因此请求X类型的auto_ptr将获得一个

    指向X类型的auto_ptr:

    auto_ptr<double> pd(new double);

    auto_ptr<string> ps(new string);

    new double 是new返回的指针,指向新分配的内存块。它是构造函数auto_ptr<double>的参数,即对应于

    原型中形参p的实参。同样,new string 也是构造函数的实参。其它两种智能指针使用同样的语法:

    unique_ptr<double> pdu(new double);

    shared_ptr<string> pss(new string);

    我们可以这么用它

    #include<memory>

    void remodel(std::string & str)

    {

      std::auto_ptr<std::string> ps(new std::string(str));

      ......

      if(error)

        throw exception();

      str=*ps;

      return ;

    }

    智能指针模板位于名称空间std中。

  • 相关阅读:
    python中xlrd模块
    2021, 8, 26模拟赛
    2021, 8,24 模拟赛
    每天挂 0 的小技巧
    2021,8,23 模拟赛
    异常处理
    64位 windows10,MYSQL8.0.13重置密码(忘记密码或者无法登录)
    Android仓库
    学习笔记索引
    「学习笔记」各类容斥反演总结
  • 原文地址:https://www.cnblogs.com/li-peng/p/3520413.html
Copyright © 2011-2022 走看看