shared_ptr 是为了解决 auto_ptr 在对象所有权上的局限性(auto_ptr 是独占的), 在使用引用计数的机制上提供了可以共享所有权的智能指针, 当然这需要额外的开销:
(1) shared_ptr 对象除了包括一个所拥有对象的指针外, 还必须包括一个引用计数代理对象的指针。
(2) 时间上的开销主要在初始化和拷贝操作上, *和->操作符重载的开销跟auto_ptr是一样。
(1) shared_ptr 对象除了包括一个所拥有对象的指针外, 还必须包括一个引用计数代理对象的指针。
(2) 时间上的开销主要在初始化和拷贝操作上, *和->操作符重载的开销跟auto_ptr是一样。
(3) 开销并不是我们不使用shared_ptr的理由, 永远不要进行不成熟的优化, 直到性能分析器告诉你这一点。
代码实现:
使用单例模式进行shared_ptr的实现
#include <iostream>
using namespace std;
class RefManage
{
public:
static RefManage* getInstance()
{
return &rm;
}
private:
RefManage() :length(0)
{}
RefManage(const RefManage& rhs);
public:
void addRef(void* ptr)
{
if (ptr != NULL)
{
int index = Find(ptr);
if (index < 0)
{
/*arr[length].addr = ptr;
arr[length++].refcount++;*/
Node tmp(ptr, 1);
arr[length++] = tmp;
}
else
{
arr[index].refcount++;
}
}
}
void delRef(void* ptr)
{
if (ptr != NULL)
{
int index = Find