why enable_shared_from_this

来源:互联网 发布:怎么成为淘宝模特 编辑:程序博客网 时间:2024/05/25 21:35

为什么会有 tr1::enable_shared_from_this 这个类,一直不解,直到看了Stephan T. Lavavej给出的关于shared_ptr 的PPT。 Stephan T. Lavavej是Visual C++ Libraries Developer。

他给的例子是:

struct Ansible {
    shared_ptr<Ansible> get_shared() {
        shared_ptr<Ansible> ret(this);
        return ret;
    }
};

int main() {
    shared_ptr<Ansible> a(new Ansible);
    Ansible& r = *a;
    shared_ptr<Ansible> b = r.get_shared();
}

Result: DOUBLE DELETION

然后使用enable_shared_from_this 就对了:

struct Ansible
    : public enable_shared_from_this<Ansible> { };

int main() {
    shared_ptr<Ansible> a(new Ansible);
    Ansible& r = *a;
    shared_ptr<Ansible> b = r.shared_from_this();
}

a and b share ownership, as if:
shared_ptr<Ansible> b = a;

为什么?看看enable_shared_from_this 的实现:

template<class _Ty> class enable_shared_from_this
 { // provide member functions that create shared_ptr to this
public:
 typedef _Ty _EStype;

 shared_ptr<_Ty> shared_from_this()
  { // return shared_ptr
  return shared_ptr<_Ty>(_Wptr);
  }

 shared_ptr<const _Ty> shared_from_this() const
  { // return shared_ptr
  return shared_ptr<const _Ty>(_Wptr);
  }

protected:
 enable_shared_from_this()
  { // construct (do nothing)
  }

 enable_shared_from_this(const enable_shared_from_this& _Right)
  : _Wptr(_Right._Wptr)
  { // construct
  }

 enable_shared_from_this& operator=(const enable_shared_from_this& _Right)
  { // assign
  _Wptr = _Right._Wptr;
  return *this;
  }

 ~enable_shared_from_this()
  { // destroy (do nothing)
  }

private:
 template<class _Ty1,
  class _Ty2>
  friend void _Do_enable(
   _Ty1 *,
   enable_shared_from_this<_Ty2>*,
   _Ref_count_base *);

 mutable weak_ptr<_Ty> _Wptr;
 };

enable_shared_from_this 的member可是一个weak_ptr.

当然,从enable_shared_from_this继承后,遇到shared_ptr后,member _Wptr 是怎样工作的,另有玄机。 可以设断点在 _Do_enable 里,有助于理解。

看似简单的share_ptr, 被实现的看似危机四伏。