Author:GuangshengZhou
QQ: 825672792
智能指针
C++内存回收机制全靠程序员手动解决, 很多时候稍不留神就会存在内存泄漏,造成严重后果。现代C++引入了智能指针,对内存进行动态管理(RAII),极大的提高了C++编程效率。
现在我们来实现几个常用的智能指针(auto_ptr、share_ptr、weak_ptr),加深对智能指针的理解。
auto_ptr 实现
template<typedef T>
class auto_ptr{
public:
//desc: explicit显示申明,防止隐式转换带来隐患,比如赋值操作。(默认implicit)
//用于构造函数,一个参数或者首参除外其他参数有默认值且只传首参时有效
explicit auto_ptr(T *ptr):m_ptr(ptr), m_bown(m_ptr != nullptr){
}
~auto_ptr(){
delete m_ptr;
}
auto_ptr(const auto_ptr<T> & autoptr):m_bown(autoptr.isown())m_ptr(autoptr.release()){
}
auto_ptr& operator =(const auto_ptr<T> & autoptr){
if(&autoptr == this){
return *this;
}
relsease();
m_ptr = autoptr.release();
return *this;
}
T& operator *(){
return *m_ptr;
}
T* opera