#ifndef _SMARTPOINTER_H_ #define _SMARTPOINTER_H_ template < typename T > class SmartPointer { T* mp; public: SmartPointer(T* p = NULL) { mp = p; } SmartPointer(const SmartPointer<T>& obj) { mp = obj.mp; const_cast<SmartPointer<T>&>(obj).mp = NULL; } SmartPointer<T>& operator = (const SmartPointer<T>& obj) { if( this != &obj ) { delete mp; mp = obj.mp; const_cast<SmartPointer<T>&>(obj).mp = NULL; } return *this; } T* operator -> () { return mp; } T& operator * () { return *mp; } bool isNull() { return (mp == NULL); } T* get() { return mp; } ~SmartPointer() { delete mp; } }; #endif
#include <iostream> #include <string> #include "SmartPointer.h" using namespace std; class Test { string m_name; public: Test(const char* name) { cout << "Hello, " << name << "." << endl; m_name = name; } void print() { cout << "I'm " << m_name << "." << endl; } ~Test() { cout << "Goodbye, " << m_name << "." << endl; } }; int main() { SmartPointer<Test> pt(new Test("hello world")); cout << "pt = " << pt.get() << endl; pt->print(); cout << endl; SmartPointer<Test> pt1(pt); cout << "pt = " << pt.get() << endl; cout << "pt1 = " << pt1.get() << endl; pt1->print(); return 0; }
小结:
智能指针是C++中自动内存管理的主要手段
智能指针在各种平台上都有不同的表现形式
智能指针能够尽可能的避开内存相关的问题
STL和Qt中都提供了对智能指针的支持