#include <iostream>
#include <boost/shared_ptr.hpp>
class implementation
{
public:
~implementation() { std::cout <<"destroying implementation\n"; }
void do_something() { std::cout << "did something\n"; }
};
void test()
{
boost::shared_ptr<implementation> sp1(new implementation());
std::cout<<"The Sample now has "<<sp1.use_count()<<" references\n";
boost::shared_ptr<implementation> sp2 = sp1;
std::cout<<"The Sample now has "<<sp2.use_count()<<" references\n";
sp1.reset();
std::cout<<"After Reset sp1. The Sample now has "<<sp2.use_count()<<" references\n";
sp2.reset();
std::cout<<"After Reset sp2.\n";
}
int main()
{
test();
}
运行结果如下:
$ ./a.out
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.
请检查上面的代码。我首先不清楚的是,下面的句子是什么意思?那么 sp1 是一个指针吗?一个函数?还是指向函数的指针?是什么new implementation()
意思?sp1() 的论点?
boost::shared_ptr<implementation> sp1(new implementation());
第二个问题是和destroying implementation
的结果。但是如果被注释掉,那么结果将是:sp1.reset()
sp2.reset()
sp1.reset()
$ ./a.out
The Sample now has 1 references
The Sample now has 2 references
After Reset sp1. The Sample now has 2 references
After Reset sp2.
destroying implementation
如果我们只注释掉sp2.reset()
,那么结果将是:
$ ./a.out
The Sample now has 1 references
The Sample now has 2 references
After Reset sp1. The Sample now has 1 references
After Reset sp2.
destroying implementation
所以没有必要同时调用sp1.reset()
并sp2.reset()
释放shared_ptr,对吗?