boost::shared_ptr 属于 boost 库,定义在 namespace boost 中,包含头文件 #include<boost/smart_ptr.hpp> 便可以使用。在上面我们看到 boost::scoped_ptr 独享所有权,不允许赋值、拷贝,boost::shared_ptr 是专门用于共享所有权的,由于要共享所有权,其在内部使用了引用计数。boost::shared_ptr 也是用于管理单个堆内存对象的。
我们还是从代码开始分析:
class Simple {
public:
public:
Simple(int param = 0) {
number = param;
std::cout << "Simple: " << number << std::endl;
}
~Simple() ;
std::cout << "~Simple: " << number << std::endl;
}
void PrintSomething() {
std::cout << "PrintSomething: " << info_extend.c_str() << std::endl;
}
number = param;
std::cout << "Simple: " << number << std::endl;
}
~Simple() ;
std::cout << "~Simple: " << number << std::endl;
}
void PrintSomething() {
std::cout << "PrintSomething: " << info_extend.c_str() << std::endl;
}
public:
std::string info_extend;
int number;
};
std::string info_extend;
int number;
};
//测试函数
void TestSharedPtr1(boost::shared_ptr<Simple> memory) { // 注意:无需使用 reference (或 const reference)
memory->PrintSomething();
std::cout << "TestSharedPtr UseCount: " << memory.use_count() << std::endl;
}
void TestSharedPtr() {
boost::shared_ptr<Simple> my_memory(new Simple(1));
if (my_memory.get()) {
my_memory->PrintSomething();
my_memory.get()->info_extend = "Addition";
my_memory->PrintSomething();
(*my_memory).info_extend += " other";
my_memory->PrintSomething();
}
std::cout << "TestSharedPtr2 UseCount: " << my_memory.use_count() << std::endl;
TestSharedPtr(my_memory);
std::cout << "TestSharedPtr2 UseCount: " << my_memory.use_count() << std::endl;
//my_memory.release();// 编译 error: 同样,shared_ptr 也没有 release 函数
}
int _tmain(int argc, _TCHAR* argv[])
{
TestSharedPtr();
return 0;
}