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中。

  • 相关阅读:
    第10件事 向优秀产品学习的学问
    第9件事 产品定位要解决的6个问题
    第8件事 3步打造产品的独特气质
    Git 从服务器取得最新代码覆盖本地
    Git:代码冲突常见解决方法
    oracle线程数更改
    从Git仓库中恢复已删除的分支、文件或丢失的commit
    Sublime 3114 + 转换GBK方法
    教你快速写出多线程Junit单元测试用例
    Spring中加载xml配置文件的六种方式
  • 原文地址:https://www.cnblogs.com/li-peng/p/3520413.html
Copyright © 2011-2022 走看看