RefPtr and PassRefPtr基础 -- WebKit中的引用计数
历史
原始指针
// example, not preferred style class Document { ... Title* m_title; } Document::Document () : m_title(0) { } Document::~Document () { if (m_title ) m_title->deref(); } void Document ::setTitle(Title* title) { if (title ) title->ref (); if (m_title ) m_title->deref(); m_title = title ; }
RefPtr
// example, not preferred style class Document { ... RefPtr<Title> m_title; } void Document ::setTitle(Title* title) { m_title = title ; }
// example, not preferred style; should use RefCounted and adoptRef (see below) RefPtr<Node> createSpecialNode() { RefPtr<Node> a = new Node; a->setSpecial(true ); return a ; } RefPtr<Node> b = createSpecialNode();
PassRefPtr
// example, not preferred style; should use RefCounted and adoptRef (see below) PassRefPtr<Node> createSpecialNode() { PassRefPtr<Node> a = new Node; a->setSpecial(true ); return a ; } RefPtr<Node> b = createSpecialNode();
// warning, will dereference a null pointer and will not work static RefPtr <Ring> g_oneRingToRuleThemAll; void finish (PassRefPtr<Ring> ring) { g_oneRingToRuleThemAll = ring ; ... ring->wear(); }
static RefPtr <Ring> g_oneRingToRuleThemAll; void finish (PassRefPtr<Ring> prpRing) { RefPtr<Ring> ring = prpRing; g_oneRingToRuleThemAll = ring ; ... ring->wear(); }
混合使用RefPtr和PassRefPtr
// example, not preferred style; should use RefCounted and adoptRef (see below) PassRefPtr<Node> createSpecialNode() { RefPtr<Node> a = new Node; a->setCreated(true ); return a .release(); } RefPtr<Node> b = createSpecialNode();
混合使用raw pointers
RefPtr<Node> a = createSpecialNode(); Node* b = getOrdinaryNode(); // the * operator *a = value; // the -> operator a->clear (); // null check in an if statement if (a ) log("not empty" ); // the ! operator if (!a ) log("empty" ); // the == and != operators, mixing with raw pointers if (a == b) log("equal" ); if (a != b) log("not equal" ); // some type casts RefPtr<DerivedNode> d = static_pointer_cast<DerivedNode>(a);
// warning, requires a pointer that already has a ref RefPtr<Node> node = adoptRef(rawNodePointer);
// warning, results in a pointer that must get an explicit deref RefPtr<Node> node = createSpecialNode(); Node* rawNodePointer = node.release ().leakRef();
PassRefPtr<T > RefPtr<T >::release() { PassRefPtr<T > tmp = adoptRef( m_ptr); m_ptr = nullptr; return tmp ; }
template<typename T> inline PassRefPtr< T> adoptRef (T* p) { adopted(p ); return PassRefPtr <T>(p, PassRefPtr< T>::Adopt ); }
template< typename T > inline T* PassRefPtr< T>::leakRef () const { T* ptr = m_ptr; m_ptr = nullptr ; return ptr ; }
RefPtr和新对象
// preferred style PassRefPtr<Node> Node::create() { return adoptRef(new Node); } RefPtr<Node> e = Node::create();
// preferred style PassRefPtr<Node> createSpecialNode() { RefPtr<Node> a = Node::create(); a->setCreated(true ); return a .release(); } RefPtr<Node> b = createSpecialNode();
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。