zoukankan      html  css  js  c++  java
  • boost::share_ptr用法

    boost中提供了几种智能指针方法:scoped_ptr shared_ptr intrusive_ptr weak_ptr,而标准库中提供的智能指针为auto_ptr. 
    这其中,我最喜欢,使用最多的是shared_ptr,也最让人随心所欲. 
    使用很简单,如下: 
    头文件 <boost/shared_ptr.hpp> 
    class A 

      virtual void process(); 

    boost::shared_ptr<A> test(new A); 
    boost::shared_ptr通过重载->(返回传入的指针),test的使用就如同一个指针。其实test是一个对象。 
    当发生引用时,boost::shared_ptr<A> test1 = test; test1与test共享构造的A指针,引用计算加一。当析够发生时,计算器减一,当计数器为0,删除内嵌指针。 

    常用的boost::shared_ptr函数有: 
    get() 获取裸指针 
    reset() 计数器减一 

    另外,boost::shared_ptr可以方便的和std::vector配合,除了不用担心节点的野指针等问题,还有一个比较有意思的功能。 
    class B : public A 

    virtual void process(); 
    void do(); 

    std::vector< boost::shared_ptr<A> > vect; 
    boost::shared_ptr<B> node = boost::shared_ptr<B>(new B); 
    vect.push_back(node); 
    vect[0]->do(); //可以很方便的访问B::do(),要知道do()并不是A的方法。 
    boost::shared_ptr有个一个缺点,就是不能从this指针构造。在boost库中,提供了一个解决方案。 
    #include <boost/enable_shared_from_this.hpp> 
    class C: public boost::enable_shared_from_this<C> // 


    这个情况出现在什么时候呢,如: 
    class D 

    public: 
    void Go(boost::shared_ptr<C> &d); 

    而D的Go方法在C中被使用,这个时候,就需要从this指针构造C的智能指针(boost::shared_from_this()方法提供)。当然,这种方法有一个前提,那就是C在外部的形态也是智能指针。 

    最后,对所有智能指针做一下简单的介绍吧。 
    auto_ptr 标准库中的智能指针。但是会转移所有权,如a = b时;内嵌的指针转移到b,智能指针a访问内嵌的指针则为空。 
    scoped_ptr 与auto_ptr类似,但是不允许复制; 
    intrusive_ptr是shared_ptr侵入式版本。使用情况,内部以及编写好了自己的内部引用计算器的代码,而又没有时间重写它。intrusive_ptr可以从this构造。 
    weak_ptr是智能指针shared_ptr的观察者。

  • 相关阅读:
    codeforces 707D-(DFS+bitset)
    codeforces Educational Codeforces Round 16-E(DP)
    codeforces 597C (树状数组+DP)
    codeforces #round363 div2.C-Vacations (DP)
    Codeforces Round #365 (Div. 2)-D Mishka and Interesting sum(树状数组)
    codeforces round367 div2.C (DP)
    June Challenge 2018 Division 2
    Codeforces Round #487 (Div. 2)
    Educational Codeforces Round 45 (Rated for Div. 2)
    [Offer收割]编程练习赛63
  • 原文地址:https://www.cnblogs.com/lidabo/p/3911446.html
Copyright © 2011-2022 走看看