Boost.smart_ptr.shared_ptr--2

来源:互联网 发布:uefi双硬盘安装ubuntu 编辑:程序博客网 时间:2024/06/05 06:06
// shared_ptr.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>
#include <boost\smart_ptr\shared_ptr.hpp>  //shared_ptr类文件
#include <boost\make_shared.hpp>          //make_shared类文件
#include <string>
using namespace boost;
using namespace std;
/********************************************************************
*shared_ptr类指针知识点:
(1)shared_ptr智能指针是最接近原指针的,它具有了原指针的一切操作,应用范围最广;
(2)用法:
     ①shared_ptr<T> sp(new T());
     ②可以赋值,比较操作指针;
*shared_ptr类成员函数
(1)reset函数:作用将引用当前指针的计数减1,停止对指针的共享;如果计数不为0,不删除;
(2)unique函数用来检查指针是否是唯一的,当唯一的时候,返回true;
(3)重载了比较赋值等运算
(4)可以用到容器中,可以使用容器作为元素;可以作为容器的元素,这个重点,容器中存放的是指针,可以理解为指针数组;
 (5) use_count统计了当前的引用计数
 ********************************************************************/

class Test
{
    public:
    Test(string a)
    {
        this->a=a;
    }
    string a;
    ~Test()
    {
        cout<<a<<" Test over"<<endl;
    }
};
int _tmain(int argc, _TCHAR* argv[])
{    
    boost::shared_ptr<Test> spTest1(new Test("Test1"));  //指针对象1
    cout <<"spTest1 count:"<<spTest1.use_count()<<spTest1->a<<endl;
    boost::shared_ptr<Test> spTest2(spTest1);
    boost::shared_ptr<Test> spTest3(spTest1);
    cout <<"spTest1 count:"<<spTest1.use_count()<<spTest1->a<<endl;
    spTest3->a="modofy";
    cout <<"spTest1 count:"<<spTest1.use_count()<<spTest1->a<<endl;
    cout<<"*******************************************************"<<endl;
    boost::shared_ptr<Test> spTest4(boost::make_shared<Test>("Test4"));//指针对象2,使用工厂函数类
    spTest3=spTest4;
    cout <<"spTest1 count:"<<spTest1.use_count()<<spTest1->a<<endl;
    cout <<"spTest3 count:"<<spTest4.use_count()<<spTest4->a<<endl;
    cout <<"spTest4 count:"<<spTest4.use_count()<<spTest4->a<<endl;
    return 0;

}

可以看到结果,shared_ptr可以像裸指针那样任意的操作,并且保证了安全,指针被引用一次就计数加1,反之则减1;



原创粉丝点击