/* 智能指针shared_ptr注意点 */
#include <iostream>
#include <string>
#include <memory> //智能指针头文件
/*
注意点一:shared_ptr并非线程安全
注意点二:weak_ptr一起使用时, weak_ptr 在使用前需要检查合法性
注意点三:shared_ptr 不支持数组, 如果使用数组, 需要自定义删除器, 如下是一个利用 lambda 实现的删除器:
*/
// shared_ptr定制的删除器仿函数
template<class T>//注意这里有模版
struct DelArray
{
void operator()(const T* ptr)
{
delete[] ptr;
ptr = NULL;
}
};
void test()
{
std::weak_ptr<int> wp;
{
std::shared_ptr<int> sp(new int); //sp.use_count()==1
wp = sp; //wp不会改变引用计数,所以sp.use_count()==1
std::shared_ptr<int> sp2 = wp.lock(); //wp没有重载->操作符。只能这样取所指向的对象
}
printf("expired:%d\n", wp.expired()); // 判断wp是否已经失效
std::shared_ptr<int> sp_null = wp.lock(); //sp_null .use_count()==0;
/*
上述代码中 sp 和 sp2 离开了作用域, 其容纳的对象已经被释放了. 得到了一个容纳 NULL 指针的 sp_null 对象.
在使用 wp 前需要调用 wp.expired() 函数判断一下. 因为 wp 还仍旧存在, 虽然引用计数等于0,仍有某处“全局”性的存储块保存着这个计数信息.
直到最后一个 weak_ptr 对象被析构, 这块“堆”存储块才能被回收, 否则 weak_ptr 无法知道自己所容纳的那个指针资源的当前状态.
*/
//shared_ptr 不支持数组
std::shared_ptr<int> sps(new int[10], DelArray<int>());
for (size_t i = 0; i < 5; i++)
{
*((int*)sps.get() + i) = 10 - i;
}
for (size_t i = 0; i < 5; i++)
{
printf("%d -- %d\n", i, *((int*)sps.get() + i));
}
}
int main()
{
test();
getchar();
return 0;
}