您的位置:首页 > 编程语言 > C语言/C++

careercup-C和C++ 13.8

2014-12-11 12:59 183 查看
13.8 编写一个智能指针类。智能指针是一种数据类型,一般用模板实现,模拟指针行为的同时还提供自动垃圾回收机制。它会自动记录SmartPointer<T*>对象的引用计数,一旦T类型对象的引用计数为零,就会释放该对象。

解法:

智能指针跟普通指针一样,但他借助自动化内存管理保证了安全性,避免了诸如悬挂指针、内存泄漏和分配失败等问题。

智能指针必须为给定对象的所有引用维护单一引用计数。主要实现构造函数、复制构造函数和赋值运算符,析构函数。

C++实现代码:

#include<iostream>
#include<cstdlib>
#include<new>
using namespace std;

template <typename T>
class SmartPointer
{
public:
SmartPointer(T* ptr)
{
ref=ptr;
ref_count=(unsigned*)malloc(sizeof(unsigned));
*ref=1;
}
SmartPointer(SmartPointer<T> &sptr)
{
ref=sptr.ref;
ref_count=sptr.ref_count;
++(*ref_count);
}
SmartPointer<T> &operator=(SmartPointer<T> &sptr)
{
if(this==&sptr) return *this;
if(*ref_count>0)
{
remove();
}
ref=sptr.ref;
ref_count=sptr.ref_count;
++(*ref_count);
return *this;
}
~SmartPointer()
{
remove();
}

T getValue()
{
return *ref;
}
protected:
void remove()
{
--(*ref_count);
if(*ref_count==0)
{
delete ref;
free(ref_count);
ref=NULL;
ref_count=NULL;
}
}
private:
T* ref;
unsigned *ref_count;
};

int main()
{
int *p1=new int();
*p1=1111;
int *p2=new int();
*p2=22222;
SmartPointer<int> sp1(p1),sp2(p2);
SmartPointer<int> spa=sp1;
sp2=spa;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: