osg(OpenSceneGraph)学习笔记1:智能指针osg::ref_ptr<>
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); } }