《程序员面试金典》(第六版)习题:仅为记录一下以加强印象,不为商业用途,如有侵权请联系删除。以下源码和解释参考了书中源码以及解释。
这里相当于是自己实现一个智能指针。智能指针主要用于方便动态内存的管理,如果自己手动使用
n
e
w
new
new和
d
e
l
e
t
e
delete
delete或
m
a
l
l
o
c
malloc
malloc和
f
r
e
e
free
free来管理动态内存的话比较困难,因为很难知道具体在哪个地方释放内存,这就会造成内存泄漏等问题。智能指针允许多个指针指向同一个对象并维持一个引用计数来记录目前对象T被引用的次数,当引用计数为0时表明此时已经没有引用对象T的地方,这时会自动释放对象T的内存,而不用手动去处理。其实在
c
+
+
c++
c++的
m
e
m
o
r
y
memory
memory头文件中已经有现成的智能指针
s
t
d
:
:
s
h
a
r
e
d
_
p
t
r
std::shared\_ptr
std::shared_ptr,具体可以查看这里这里。
template<class T> class SmartPointer
{
protected:
T* ref;//指向的对象
unsigned* refCount;//引用计数
void remove()
{
--(*refCount);
if (*refCount == 0)//引用计数为0时
{
delete ref;
free(refCount);
ref = nullptr;
refCount = nullptr;
}
}
public:
SmartPointer(T* ptr)
{
ref = ptr;
refCount = (unsigned*)malloc(sizeof(unsigned));
*refCount = 1;
}
SmartPointer(SmartPointer<T>& sptr)
{
ref = sptr.ref;
refCount = sptr.refCount;
++(*refCount);
}
SmartPointer<T>& operator=(SmartPointer<T> & sptr)
{
if (this == &sptr)
return *this;
if (*refCount > 0)
remove();
ref = sptr.ref;
refCount = sptr.refCount;
++(*refCount);
return *this;
}
~SmartPointer()
{
remove();
}
T getValue()
{
return *ref;
}
};