boost库 shared_ptr (复习用,无参考价值)

来源:互联网 发布:破解苹果mac密码 编辑:程序博客网 时间:2024/05/14 09:22
#include <iostream>#include <String>#include <cassert>#include <boost/shared_ptr.hpp>using namespace std;class A{    boost::shared_ptr<int> no_;public:    A(boost::shared_ptr<int> no):no_(no){}    void value(int i)    {        *no_=i;    }};class B{    boost::shared_ptr<int> no_;public:    B(boost::shared_ptr<int> no):no_(no){}    int value()    {        return *no_;    }};int main(){    boost::shared_ptr<int> temp(new int(14));    A a(temp);    B b(temp);    a.value(28);    assert(b.value()==28);    return 0;}


shaed_ptr 另类用法,即指针类似FILE*类型的并不能delete之,而是用fileClose关闭之,此时上述方法就行不通了。这里给出代码,一个解决方法

boost导论上的代码。原封不动放过来。大家仔细看看。

#include <iostream>#include <boost/shared_ptr.hpp>class FileCloser{public:    void operator()(FILE *file)    {        std::cout<<"The FileCloser has been called with a FILE*,whick will now be closed.\n";        if(file!=0)        {            fclose(file);        }    }};using namespace std;int main(){    std::cout<<"A shared_ptr sample"<<std::endl;    FILE * f=fopen("test.txt","r");    if(f==0)    {        std::cout<<"Unable to open file \n";        throw "Unable to open file";    }    boost::shared_ptr<FILE> my_shared_file(f,FileCloser());    //position of the file pointer    fseek(my_shared_file.get(),42,SEEK_SET);    std::cout<<"By new ,the FILE has been closed!\n";    return 0;}