一、智能指针
为了防止内存泄漏,而设计的一个管理类,主要是对资源引用的计数;其实就是一个引用计数器,当资源被使用时,计数器加1,释放时,计数器减1,当减至0时,内存释放不用。
我们看一下osg的超级指针osg::ref_ptr<T>Class Template Reference,其成员如下:
ref_ptr () | |
ref_ptr (T *ptr) | |
ref_ptr (const ref_ptr &rp) | |
template<class Other> | |
ref_ptr (const ref_ptr< Other > &rp) | |
ref_ptr (observer_ptr< T > &optr) | |
~ref_ptr () | |
ref_ptr & | operator= (const ref_ptr &rp) |
template<class Other> | |
ref_ptr & | operator= (const ref_ptr< Other > &rp) |
ref_ptr & | operator= (T *ptr) |
bool | operator== (const ref_ptr &rp) const |
bool | operator== (const T *ptr) const |
bool | operator!= (const ref_ptr &rp) const |
bool | operator!= (const T *ptr) const |
bool | operator< (const ref_ptr &rp) const |
operator unspecified_bool_type () const | |
T & | operator* () const |
T * | operator-> () const |
T * | get () const |
bool | operator! () const |
bool | valid () const |
T * | release () |
void | swap (ref_ptr &rp) |
int osg::Referenced::ref ( ) const
int osg::Referenced::unref ( ) const
二、自定义超级指针
模仿osg的智能指针,我们定义如下模板类:sup_ptr<T>
template <class T>
class sup_ptr{
public:
sup_ptr(){
_ptr=NULL;
}
sup_ptr(T *ptr){
_ptr=ptr;
if(_ptr)
{
_ptr->ref();//引用计数加1
}
}
~sup_ptr()
{
if(_ptr)
{
_ptr->unref();//引用计数减1
}
}
//重载运算符=
sup_ptr& operator= (T *p)
{
T *temp = _ptr;
_ptr = p;
if(_ptr)
{
_ptr->ref();
}
if(temp)
{
temp->unref();
}
return *this;
}
//重载运算符*
T& operator*()
{
return *_ptr;
}
//重载运算符()
operator T* () const
{
return _ptr;
}
//重载运算符->
T * operator-> () const
{
return _ptr;
}
//重载get方法
T * get () {
return _ptr;
}
private:
T *_ptr;
};
三、使用自定义超级指针
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
osgQt::initQtWindowingSystem();
sup_ptr<osgViewer::Viewer> viewer = new osgViewer::Viewer;
sup_ptr<osg::Group> root= new osg::Group;
root->addChild(osgDB::readNodeFile("glider.osg"));
root->addChild(osgDB::readNodeFile("osgcool.osgt"));
viewer->setSceneData(root);
viewer->setCameraManipulator(new osgGA::TrackballManipulator);
viewer->addEventHandler(new osgViewer::StatsHandler);
osgQt::GLWidget * glw= new osgQt::GLWidget;
osgQt::GraphicsWindowQt * graphic= new osgQt::GraphicsWindowQt(glw);
osgQt::setViewer(viewer);
viewer->getCamera()->setGraphicsContext(graphic);
viewer->getCamera()->setViewport(new osg::Viewport(0,0,glw->width(),glw->height()));
glw->show();
return a.exec();
}四、运行效果如下: