OSG的智能指針,osg::ref_ptr<>
osg::Referenced類管理引用計數內存塊,osg::ref_ptr需要使用以它為基類的其它類作為模板參數。
osg::ref_ptr<>類模板重新實現了一系列C++重載符和成員函數,主要有:
- T* get(): 返回管理的指針, { return _ptr; }
- T& operator*(): 返回間接引用,{ return *_ptr; }
- T* operator->(): { return _ptr; }
- operator=(): 各種賦值
- operator==(), operator!=(), and operator!():
- valid(): { return _ptr!=0; }
- release():
簡單示例:
#include <osg/ref_ptr> #include <osg/Referenced> #include <iostream> class MonitoringTarget : public osg::Referenced { public: MonitoringTarget(int id) : _id(id) { std::cout << "構造目標 " << _id << std::endl; } protected: virtual ~MonitoringTarget() { std::cout << "目標銷毀 " << _id << std::endl; } int _id; }; int main(int argc, char *argv[]) { osg::ref_ptr<MonitoringTarget> target = new MonitoringTarget(0); std::cout << "引用前引用計數為: " << target->referenceCount() << std::endl; osg::ref_ptr<MonitoringTarget> anotherTarget = target; std::cout << "引用后引用計數為: " << target->referenceCount() << std::endl; for (unsigned int i = 1; i<5; ++i) { osg::ref_ptr<MonitoringTarget> subTarget = new MonitoringTarget(i); } }