zoukankan      html  css  js  c++  java
  • [3] 智能指针std::auto_ptr

    【1】std::auto_ptr

    对于编译器来说,智能指针实质是一个栈对象,而并非指针类型。

    智能指针通过构造函数获取堆内存的管理所有权,而在其生命期结束时,再通过析构函数释放由它所管理的堆内存。

    所有智能指针都重载了“operator->”操作符,直接返回对象的引用,用以操作对象。访问智能指针原来的方法则使用“.”操作符。

    访问智能指针包含的裸指针则可以用get()函数。

    由于智能指针是一个对象,所以if(spObject)永远为真。要判断智能指针的裸指针是否为空,需要这样判断:if(spObject.get())。

    智能指针包含了reset()方法,如果不传递参数(或传递NULL),则智能指针会释放当前管理的内存。如果传递一个对象,则智能指针会释放当前对象,来管理新传入的对象。

    【2】std::auto_ptr 示例及分析

    <1>代码如下:

     1 #include<iostream>
     2 #include<memory>
     3 using namespace std;
     4 
     5 class Int
     6 {
     7 public:
     8     Int(int nValue = 0) 
     9     {
    10         m_nValue = nValue;
    11         std::cout << "Constructor: " << m_nValue << std::endl; 
    12     }
    13     ~Int() 
    14     {
    15         std::cout << "Destructor: " << m_nValue << std::endl;
    16     }
    17     void PrintValue()
    18     {
    19         std::cout << "PrintValue: " <<m_nValue<< std::endl;
    20     }
    21     void SetValue(int nSetValue)
    22     {
    23         m_nValue = nSetValue;
    24     }
    25 
    26 private:
    27     int m_nValue;
    28 };
    29 
    30 void TestAuto_Ptr1() 
    31 {
    32     std::auto_ptr<Int>    spInt(new Int(10));   // 创建对象
    33     if (spInt.get())                     // 判断智能指针是否为空
    34     { 
    35         spInt->PrintValue();        // 使用operator->调用智能指针对象的函数
    36         spInt.get()->SetValue(20);    // 使用get()返回裸指针,然后通过裸指针调用的成员函数
    37         spInt->PrintValue();        // 再次打印,检验上步赋值成功
    38         (*spInt).SetValue(30);        // 使用operator*返回智能指针内部对象,然后用“.”调用智能指针对象中的函数
    39         spInt->PrintValue();        // 再次打印,表明上步赋值成功            
    40     }
    41     //spInt栈对象结束生命期,随之析构堆对象Int(10),同时释放内存资源
    42 }
    43 
    44 void main()
    45 {
    46     TestAuto_Ptr1();
    47 }
    48 
    49 //执行结果如下:
    50 /*
    51 Constructor: 10
    52 PrintValue: 10
    53 PrintValue: 20
    54 PrintValue: 30
    55 Destructor: 30
    56 */

    上面为一般情况下使用std::auto_ptr的代码示例,一切看似都蛮不错哈,说一千道一万,无论如何不用咱们再显式使用那该死的delete了。

    但是,实际的使用中的情况要比这个复杂得多,也不选多么复杂的!眼下咱比如:智能指针的拷贝构造以及赋值构造等。请看以下分析。

    <2> 添加测试函数2

    代码以及注释如下:

     1 void TestAuto_Ptr2() 
     2 {
     3     std::auto_ptr<Int> spInt(new Int(1));
     4     if (spInt.get()) 
     5     {
     6         std::auto_ptr<Int> spInt2;   // 创建一个新的spInt2对象
     7         spInt2 = spInt;              // 复制旧的spInt给spInt2
     8         spInt2->PrintValue();        // 输出信息,复制成功
     9         spInt->PrintValue();         // 崩溃
    10     }
    11 }

    最终可以看到如上代码导致崩溃!居然崩溃了?什么原因导致崩溃呢?

    在网上看到各种版本的解释。赵本山大叔有一句话:“你刨得不深,我要往祖坟上刨!”

    跟进std::auto_ptr的源码,其赋值构造函数代码如下:

     1 //std::auto_ptr赋值构造函数
     2 
     3 _Myt& operator=(_Myt& _Right) _THROW0()
     4 {    // assign compatible _Right (assume pointer)
     5     reset(_Right.release());
     6     return (*this);
     7 }
     8 
     9 _Ty *release() _THROW0()
    10 {    // return wrapped pointer and give up ownership
    11     _Ty *_Tmp = _Myptr;
    12     _Myptr = 0;
    13     return (_Tmp);
    14 }
    15 
    16 void reset(_Ty *_Ptr = 0)
    17 {    // destroy designated object and store new pointer
    18     if (_Ptr != _Myptr)
    19         delete _Myptr;
    20     _Myptr = _Ptr;
    21 }

    三个函数,调用关系一目了然,执行结果很清晰:目标对象获取源对象所管理的内存所有权,同时把源对象置空。

    通过上面的源码分析,我们可以看到: 崩溃的罪魁祸首是 spInt2 = spInt; 就这行代码,发生两个重要过程:

    1> spInt2完全夺取了spInt的内存管理所有权;

    2> 置spInt为空。

    由于spInt已置为空,最后再使用必然导致崩溃。

     

    细心的人估计看到了源码函数后面的那个关键字throw,关于这个关键字请参见随笔《函数后面加throw关键字

     

    所以,使用std::auto_ptr时,绝对不能使用“operator=”操作符。

    这也正所谓std::auto_ptr是支持毁坏式复制语义及RAII的智能指针的全部体现。

    关于RAII惯用法,请参见随笔《RAII惯用法详解》。

     

    好吧!再看一种实际使用的例子,代码如下:

    1 void TestAuto_Ptr3() 
    2 {
    3     std::auto_ptr<Int> spInt3(new Int(100));
    4 
    5     if (spInt3.get()) 
    6     {
    7         spInt3.release();
    8     }
    9 }

    执行结果为:Constructor: 100

    看到有什么异常了吗?没有输出“Destructor: 100”,那也就意味着我们创建出来的对象竟然没有被析构,这个可不科学!

    上面我们才强调了std::auto_ptr是RAII的智能指针,这里没有析构对象是否导致内存泄漏呢?

    当我们不想让spInt3继续生存下去时,第一反应应该是调用release()函数释放内存,结果却导致内存泄漏。

    在内存受限系统中,假如spInt3占用太多内存,我们会考虑一旦使用完成后,立刻归还,而不是等到spInt3结束生命期后才归还。

    由于上面已经有release()函数的实现源码,所以,这里的内存泄漏原因其实很明白,不再赘述。

     

    那么正确的代码应该是怎样呢?根据上面的实际需求再不导致内存泄漏情况下,如下实现:

     1 void TestAuto_Ptr3() 
     2 {
     3     std::auto_ptr<Int> spInt3(new Int(100));
     4     if (spInt3.get()) 
     5     {
     6         Int* pInt = spInt3.release();
     7         delete pInt;
     8     }
     9 }
    10 //
    11 void TestAuto_Ptr3()
    12 {
    13     std::auto_ptr<Int> spInt3(new Int(100));
    14     if (spInt3.get()) 
    15     {
    16         spInt3.reset();  // 释放spInt3内部管理的内存
    17     }
    18 }

    <3> 总结:关于std::auto_ptr的使用,请注意以下几点:

    (1)尽量不要使用“operator=”(如果使用了,请不要再使用先前对象)。

    (2)记住release()函数不会释放对象,仅仅归还所有权。

    (3)std::auto_ptr最好不要当成参数传递(读者可以自行写代码确定为什么不能)。

    (4)由于std::auto_ptr的“operator=”问题,由其管理的对象不能放入std::vector等容器中。

    (5)auto_ptr存储的指针应该为NULL或者指向动态分配的内存块。

    (6)auto_ptr存储的指针应该指向单一物件(是new出来的,而不是new[]出来的)。

    (7)两个auto_ptr对象不会同时指向同一块内存块(要明白两个auto_ptr对象赋值会发生什么)。

     

    使用std::auto_ptr的局限性很大,可谓防不胜防。

     

    Good Good Study, Day Day Up.

    顺序   选择  循环  总结

  • 相关阅读:
    jqueryeasyui 使用笔记
    怎么查看端口占用情况?
    Ie6 Ie7 双倍padding
    Javascript获取URL
    fckeditor,用p替代div标签设置对齐方式
    ZenCart安全建站的几个措施和步骤
    复选框二选一 javascript
    dedecms从php设置里面去掉index.html
    ajax调用webservice返回DataTable "序列化类型为“System.Reflection.Module”的对象时检测到循环引用
    无题
  • 原文地址:https://www.cnblogs.com/Braveliu/p/3290441.html
Copyright © 2011-2022 走看看