shared_ptr 最简单应用

来源:互联网 发布:海航集团离职工龄算法 编辑:程序博客网 时间:2024/04/29 13:48

#include <cstdlib>
//多个 shared_ptr 指向同一个 内存块
//修改任何一个内存块,都是在修改多有的 shared_ptr
#include <iostream>
using namespace std;
#include <boost/shared_ptr.hpp>
using namespace boost;
#include <cassert>
class A
{
  shared_ptr<int> no_;
public:
  A(shared_ptr<int> p):no_(p){}
  void SetValue(int n){*no_ = n;}
  int GetValue()const{return *no_;}
};
class B
{
  shared_ptr<int> no_;
public:
  B(shared_ptr<int> p):no_(p){}
  void SetValue(int n){*no_ = n;}
  int GetValue()const{return *no_;}
};
void Do()
{
    shared_ptr<int> Temp(new int(10));
    A a(Temp);
    B b(Temp);
    cout<<"a 的值为 : "<<a.GetValue()<<endl;
    a.SetValue(20);
    cout<<"b 的值为 : "<<b.GetValue()<<endl;
    assert(b.GetValue() == 20);
}
int main(int argc, char *argv[])
{
    Do();
    system("PAUSE");
    return EXIT_SUCCESS;
}

原创粉丝点击