指針帶給了 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 [email protected] * @version 0.1.00 * @date 2014-04-14 */ #ifndef SMART-POINTER_H #define SMART-POINTER_H #includetemplate 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 SmartPointer ::SmartPointer(const SmartPointer &rhs) :ref_count(rhs.ref_count), ptr(rhs.ptr) { ++ *ref_count; } template SmartPointer & SmartPointer ::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*/