std::enable_shared_form_this

1.std::enable_shared_from_this<T>主要提供了一个函数 shared_form_this函数返回 std::shared_ptr<T>对象
2.能调用shared_form_this必须使用是 std::shared_ptr<T> 构建的对象,否则会抛异常std::bad_weak_ptr

  1. std::enable_shared_from_this<T>的基本结构如下,是利用了std::weak_ptr来实现,当构建std::shared_ptr对象时,会初始m_weakptr

std::enable_shared_from_this<T>{
  std::weak_ptr<T> m_weakptr;
};

根据构造函数的过程是先构造std::enable_shared_from_this<T>,再构建 T
,最后构建std::shared_ptr<T>;这时候我们可检测 T是否继承与 std::enable_shared_from_this<T>,(可利用 std::is_base_of等type_traits)
其中,GCC是使用的函数重载的最佳匹配来实现的
GCC实现了一个函数 __enable_shared_from_this_helper
其重载为

__enable_shared_from_this_helper( __shared_count<> &,
                                  enable_shared_from_this<_T> * p1,
                                  _T * p2
) /// 函数1
__enable_shared_from_this_helpr( __shared_count<>&,...) ///函数2

当继承了 std::enable_shared_from_this 时会优先调用函数1实现对std::enable_shared_from_this 中的weak_ptr赋值,而未继承std::enable_shared_from_this的只好走函数2不做任何操作
一个简单的逻辑

    class A;
    void __helper( int a, A * pa){
        std::cout << "__helper (int a, A *pa)" << std::endl;
    }
    void __helper( int a, ...){
        std::cout << "__helper( int a, ... )" << std::endl;
    }
    class A{

    };
    class B : public A{
    public:
        B( ){
           int a = 10;
           __helper(a, this);
        }


    };
    class C{
    public:
        C(){
            int a = 10;
            __helper( a, this);
        }
    };
 B b; ////输出 __helper (int a, A *pa)
 C c; ////输出 __helper( int a, ... )

gcc(4.8)下不允许出现这种情况

    class C : public std::enable_shared_from_this<C>{
    };
    class D: public std::enable_shared_from_this<D> , public C{
    };

这种情况编译会出错(具体缘由不清楚(分析不来这个模板)),但是vc++(2017)允许,但是用shared_from_this会出错

© 版权声明
THE END
如果内容对您有所帮助,就支持一下吧!
点赞0 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容