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);
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM