ref_ptr<>模板类的定义如下:
template<class T>
class ref_ptr { public: typedef T element_type;
ref_ptr() : _ptr(0) {} ref_ptr(T* ptr) : _ptr(ptr) { if (_ptr) _ptr->ref(); } ref_ptr(const ref_ptr& rp) : _ptr(rp._ptr) { if (_ptr) _ptr->ref(); } template<class Other> ref_ptr(const ref_ptr<Other>& rp) : _ptr(rp._ptr) { if (_ptr) _ptr->ref(); }
~ref_ptr() { if (_ptr) _ptr->unref(); _ptr = 0; }
ref_ptr& operator = (const ref_ptr& rp) { assign(rp); return *this; }
template<class Other> ref_ptr& operator = (const ref_ptr<Other>& rp) { assign(rp); return *this; }
inline ref_ptr& operator = (T* ptr) { if (_ptr==ptr) return *this; T* tmp_ptr = _ptr; // 存放原先指针的临时变量 _ptr = ptr; // 更新原先的那个指针 if (_ptr) _ptr->ref(); //如果新的这个指针变量值为真,那么对应的引用计数值加1 // unref second to prevent any deletion of any object which might // be referenced by the other object. i.e rp is child of the // original _ptr. if (tmp_ptr) tmp_ptr->unref(); //如果原先的那个指针变量值为真,那么引用计数值减1 return *this; }
T& operator*() const { return *_ptr; } T* operator->() const { return _ptr; } T* get() const { return _ptr; }
bool operator!() const { return _ptr==0; } // not required bool valid() const { return _ptr!=0; }
T* release() { T* tmp=_ptr; if (_ptr) _ptr->unref_nodelete(); _ptr=0; return tmp; }
void swap(ref_ptr& rp) { T* tmp=_ptr; _ptr=rp._ptr; rp._ptr=tmp; }
private:
T* _ptr; };
这个类的定义即: class ref_ptr<T* >,ref_ptr类中有一个指向T类型的智能指针。
osg::ref_ptr<osg::Geode> geode = new osg::Geode();
这行代码的意思是: new osg::Geode(); 返回了一个指针,指向叶节点 osg::Geode() 的指针。
geode 是类ref_ptr<>的一个对象,对象中有一个osg::Geode类型的智能指针,这个指针被赋值为右边 new osg::Geode(); 返回的那个指针。 因此凡是对叶节点 osg::Geode() 的操作都要使用指针的操作,即要使用 -> 来操作。