-
课程目标
— 完成SharedPointer
类的具体实现
-
SharedPointer
类的设计要点
-
计数机制原理剖析
-
SharedPointer
类的声明
-
智能指针的比较
由于SharedPointer
支持多个对象同时指向一片堆空间,因此必须支持比较操作
SharedPointer.h
#ifndef SHAREDPOINTER_H
#define SHAREDPOINTER_H
#include <cstdlib>
#include "Pointer.h"
#include "Exception.h"
namespace XiebsLib
{
template <typename T>
class SharedPointer : public Pointer<T>
{
protected:
int* m_ref;
void assign(const SharedPointer<T>& obj)
{
this->m_ref = obj.m_ref;
this->m_pointer = obj.m_pointer;
if(this->m_ref)
{
(*this->m_ref)++;
}
}
public:
SharedPointer(T* p = nullptr) : m_ref(nullptr)
{
if(p != nullptr)
{
m_ref = reinterpret_cast<int*>(std::malloc(sizeof(int)));
if(m_ref != nullptr)
{
(*m_ref) = 1;
this->m_pointer = p;
}
else
{
THROW_EXCEPTION(NoEnoughMemoryException, "no enough to create m_ref Object");
}
}
}
SharedPointer(const SharedPointer<T>& obj):Pointer<T>(nullptr)
{
assign(obj);
}
SharedPointer<T>& operator=(const SharedPointer<T>& obj)
{
if(this != &obj)
{
clear();
assign(obj);
}
return *this;
}
void clear()
{
T* toDel = this->m_pointer;
int* ref = this->m_ref;
this->m_pointer = nullptr;
this->m_ref = nullptr;
if(ref != nullptr)
{
(*ref)--;
if((*ref) == 0)
{
free(ref);
delete toDel;
}
}
}
~SharedPointer()
{
clear();
}
};
template <typename T>
bool operator==(const SharedPointer<T>& l, const SharedPointer<T>& r)
{
return (l.get() == r.get());
}
template <typename T>
bool operator!=(const SharedPointer<T>& l, const SharedPointer<T>& r)
{
return (!(l == r));
}
}
#endif // SHAREDPOINTER_H
-
智能指针使用军规
-
小结:
— SharedPointer 最大程度的模拟了原生指针的行为
— 计数机制确保多个智能指针合法的指向同一片堆空间
— 智能指针只能用于指向堆空间中的内存
— 不同类型的智能指针不要混合使用
—堆对象的生命周期由智能指针管理
正确的代码在27-2