一点都不智能的智能指针
#include <iostream> using namespace std; template<typename T> class Auto { public: // 避免编译器报错,需要显式类型转换 explicit Auto(T* data = NULL) : m_data(data) {} // 转移拷贝 Auto(Auto<T>& that) : m_data(change(that)) {} // 转移赋值 Auto& operator = (Auto<T>& that) { if (this != &this) return release(change(that)); return *this; } ~Auto(void) { delete m_data; } T& operator * (void) { return *m_data; } T const& operator * (void) const { return *(const_cast<Auto&>(*this)); } T* operator -> (void) { return m_data; } T *const operator ->(void) const { return m_data; } friend ostream& operator << (ostream& os, Auto const& rhs) { return os << rhs.m_data; } private: T* change(Auto<T>& that) { T* temp = that.m_data; that.m_data = NULL; return temp; } Auto& release(T* data) { delete m_data; m_data = data; return *this; } T* m_data; }; // 特化数组类型的 template<typename T> class Auto<T[]> { public: explicit Auto(T* data = NULL) : m_data(data) {} Auto(Auto<T>& that) : m_data(change(that)) {} Auto& operator = (Auto<T>& that) { if (that != *this) return release(change(that)); return *this; } ~Auto(void) { delete[] m_data; } T& operator * (void) { return *m_data; } T const& operator * (void) const { return *(const_cast<Auto&>(*this)); } T* operator -> (void) { return m_data; } T *const operator ->(void) const { return m_data; } friend ostream& operator << (ostream& os, Auto const& rhs) { return os << rhs.m_data; } private: T* change(Auto<T>& that) { T* temp = that.m_data; that.m_data = NULL; return temp; } Auto& release(T* data) { delete m_data; m_data = data; return *this; } T* m_data; };
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-10-14 10:16:20