C++ Primer----智能指针类 2
指针带给了 C++巨大的灵活性,然而同样也带来无数的问题,悬挂指针,内存泄漏等。
int *pInt = new int(1); // Do not forget delete pInt;
智能指针就是一种能够有效避免悬挂指针的方法。通过一个类,来管理指针的复制,
delete 等。从而使用户可以放心地使用指针。
一种智能指针的实现方法是,通过一个计数,追踪当前指向同一块地址的指针有多少个,
当没有指针指向这块地址的时候,自动释放资源。从而有效地避免了 内存泄漏 和 悬挂指针问题。
// Last Update:2014-04-14 10:49:34
/**
* @file smart-pointer.h
* @brief Smart Pointer using reference counting
* @author shoulinjun@126.com
* @version 0.1.00
* @date 2014-04-14
*/
#ifndef SMART-POINTER_H
#define SMART-POINTER_H
#include <iostream>
template<class T>
class SmartPointer
{
public:
SmartPointer(T value)
: ptr(new T(value)), ref_count(new size_t(1)) {}
~SmartPointer() { remove(); }
//copy control
SmartPointer(const SmartPointer &rhs);
SmartPointer& operator=(const SmartPointer &rhs);
T* get_ptr() {return ptr;}
T get_ptr_val() {return *ptr;}
T& operator*() {return *ptr;}
const T& operator*()const {return *ptr;}
T* operator->() {return ptr;}
private:
T* ptr;
size_t *ref_count;
protected:
void remove(){
if(--*ref_count == 0){
delete ptr;
delete ref_count;
ptr = NULL;
ref_count = NULL;
}
}
};
template<class T>
SmartPointer<T>::SmartPointer(const SmartPointer &rhs)
:ref_count(rhs.ref_count), ptr(rhs.ptr)
{
++ *ref_count;
}
template<class T>
SmartPointer<T>& SmartPointer<T>::operator=(const SmartPointer &rhs)
{
//deal with self-assignment
++ *(rhs.ref_count);
remove();
ptr = rhs.ptr;
ref_count = rhs.ref_count;
return *this;
}
#endif /*SMART-POINTER_H*/
浙公网安备 33010602011771号