您的位置:首页 > 其它

OSG学习笔记1——智能指针

2016-04-20 09:58 337 查看
// osgStudy4_19.cpp : 定义控制台应用程序的入口点。

//智能指针对场景的引用计数,看到这里的时候几乎就想放弃了,智能指针什么鬼,在大神的鼓励下,要搞科研的人怎么能不学会钻研呢!其实还是不是特别懂,但好像稍微理解一点点了,又参考了一下C++Primer。

//——————C++的动态内存和智能指针————————————

//动态分配的对象的生存期与它们在哪里创建时无关的,只有当显式的被释放时,这些对象才会销毁。

//动态对象的正确释放在编程中很容易出错的地方,为了更安全地使用动态对象,C++标准库定义了两个智能指针类型来管理动态分配的对象。

//当一个对象应该被释放时,指向它的智能指针可以确保自动地释放它。

//——————OSG的智能指针——————————————————

//OSG提供一种“垃圾收集”机制,通过“内存引用计数”的形式来管理场景中的节点和绘制体。

//每个场景中的对象都维护者一个引用计数值(就是智能指针),当它被其他对象使用时,引用计数值+1,反之减1。

//当一个对象的引用计数为0时,它将自动从内存中释放。

#include "stdafx.h"
#include<osg/Geode>
#include<iostream>

class GeodeParent//定义了GeodeParent类,通过智能指针变量_geode来保存一个Geode类型的场景对象
{
public:
GeodeParent(){}

void setGeode(osg::Geode* geode){ _geode = geode; }
osg::Geode* getGeode(){ return _geode.get(); }

protected:
osg::ref_ptr<osg::Geode> _geode;//智能指针变量_geode
};

int _tmain(int argc, _TCHAR* argv[])
{
osg::ref_ptr<osg::Geode> geode1 = new osg::Geode;//定义了两个场景对象,geode1,2 在定义的过程中已经分别被一个智能指针引用
osg::ref_ptr<osg::Geode> geode2 = new osg::Geode;//ref_ptr1=ref_ptr2=1

GeodeParent geodeParent;//构造一个geodeParent对象
geodeParent.setGeode(geode1);//该geodeParent是有geode1来定义的,所以这里又引用到了一次geode1,ref_ptr1=2.

std::cout << "Count 1 Before"<<geode1->referenceCount()<< std::endl;//ref_ptr1=2
std::cout << "Count 2 Before" << geode2->referenceCount() << std::endl;//ref_ptr1=1

geodeParent.setGeode(geode2);//重新将geodeParent设置为geode2,没有引用geode1而引用geode2,所以ref_ptr1=1,ref_ptr2=2

std::cout << "Count 1 After" << geode1->referenceCount() << std::endl;
std::cout << "Count 2 After" << geode2->referenceCount() << std::endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: