#include <boost/smart_ptr.hpp>
#include <string>
#include <iostream>
//#include <boost/make_shared.hpp>
using namespace std;
using namespace boost;
struct posix_file
{
posix_file(const string& filename)
{
cout <<"open file" << filename << endl;
}
~posix_file()
{
cout << "close file" << endl;
}
};
class shared_ptr_tese
{
private:
shared_ptr<int> sp;
public:
shared_ptr_tese(shared_ptr<int> _sp):sp(_sp){}
void print()
{
cout << "count: " << sp.use_count() << "\tv: " << *sp<< endl;
}
};
void print(shared_ptr<int> p)
{
cout << "count: " << p.use_count() << "\tv: " << *p<< endl;
}
//smart pointer test
int main(int argc, char** argv)
{
//scoped_ptr, 不需要delete,内存自动释放
//scoped 不允许拷贝,不允许赋值,因为这都是私有的,所以也不能用于容器
scoped_ptr<string> sp(new string("this is test"));
cout << *sp << endl;
cout << sp->size()<< endl;
scoped_ptr<int> p(new int);
if(p)
{
*p=10;
cout<< *p << endl;
}
p.reset();
assert(p==0);
//结束时自动调用析构函数
scoped_ptr<posix_file> pfile(new posix_file("a.txt"));
//auto_ptr拥有指针的转移权
auto_ptr<int> ap(new int(10));
scoped_ptr<int> sp1(ap);
//scoped_ptr<int> sp1(sp1); 指针的所以权不能转移
assert(ap.get() == 0); //ap不再拥有指针
ap.reset(new int(20));
cout << "*ap" << *ap << "\t" << "*sp1" << *sp1 << endl;
//scoped_array,不过不推荐使用,因为这部分工作都可以使用vector来代替
int *arr=new int[100];
scoped_array<int> sa(arr);
for(int i=0;i<100;i++)
{
sa[i] = i; //sa+i is error
}
//shared_ptr
shared_ptr<int> shp(new int(20));
assert(shp.unique()); //现在是唯一的拥有者
shared_ptr<int> shp1(shp);
assert(shp.unique() == false);
assert(shp==shp1 && shp.use_count() == 2);//指向同一个对象,引用计数现在为2了
*shp1=50;//解引用
assert(*shp =- 50);//另外一个也跟着改变
//使用类来测试
shared_ptr<int> sp0(new int(300));
shared_ptr_tese spt1(sp0);
shared_ptr_tese spt2(sp0);
spt1.print();//count: 3 v: 300
spt2.print();//count: 3 v: 300
*sp0 = 3000;
//因为传递的不是引用,所以引用值又加1
spt1.print();//count: 3 v: 3000
print(sp0); //count: 4 v: 3000
//传入的定制删除器
shared_ptr<FILE> fp(fopen("a.txt","r"), fclose);
//shared_array
int *p1 = new int[100];
shared_array<int> psa(p1); //代理数组
shared_array<int> psa1(psa); //引用计数增加
psa[0] = 10; //使用[]访问数组
assert(psa[0] == 10);
return 0;
}
boost学习scoped_ptr,shared_ptr
最新推荐文章于 2023-08-09 11:52:31 发布