class implementation { public: ~implementation() { std::cout <<"destroying implementation "; } void do_something() { std::cout << "did something "; } }; void test() { boost::shared_ptr<implementation> sp1(new implementation()); std::cout<<"The Sample now has "<<sp1.use_count()<<" references "; boost::shared_ptr<implementation> sp2 = sp1; std::cout<<"The Sample now has "<<sp2.use_count()<<" references "; sp1.reset(); std::cout<<"After Reset sp1. The Sample now has "<<sp2.use_count()<<" references "; sp2.reset(); std::cout<<"After Reset sp2. "; }
程序输出内容:
The Sample now has 1 references
The Sample now has 2 references
After Reset sp1. The Sample now has 1 references
destroying implementation
After Reset sp2.
归纳如下:
Shared_pt可以共享内存,两个Shared_ptr之间直接用“=”赋值,每个Shared_ptr内部都有一个计数器记录该内存地址有多少个Shared_ptr持有,可以用use_count()访问。当该计数器为0时,会自动调用delete删除内存。