標準ライブラリのauto_ptrの配列バージョン。
| template<class T> class auto_array{ public: typedef T element_type; private: T* m_ptr; auto_array(); auto_array(const auto_array&); auto_array& operator=(const auto_array&); public: explicit auto_array(T* p){m_ptr = p;} ~auto_array(){ if(m_ptr) delete[] m_ptr; m_ptr = 0; } T* get() const {return m_ptr;} operator T*() const {return m_ptr;} }; |
上記のものは、私が破壊的コピーセマンティクスを使いこなせないので封印してあったバージョンです。しかし、またもや、やねうらお様から、所有権インジケータのないauto_ptrは使い物にならないとの指摘をいただきました。以下は、やねうらお氏制作のauto_arrayです。というわけで、こちらを使いましょう。(^^;
| /* auto_array : auto_ptr array programmed by yaneurao(M.Isozaki) '00/09/28 */ #ifndef __yaneAutoArray_h__ #define __yaneAutoArray_h__ template<class T> class auto_array { public: typedef T element_type; explicit auto_array(const T* p){ m_lp = const_cast<T*>(p); m_bOwner= true; } auto_array(){ m_lp = NULL; m_bOwner = false; } auto_array(auto_array<T>&rhs){ m_lp = rhs.m_lp; m_bOwner= rhs.m_bOwner; rhs.m_bOwner = false; } // auto_array間の代入演算子 auto_array<T>& operator = (auto_array<T>& rhs){ if (this!=&rhs){ clear(); m_lp = rhs.m_lp; m_bOwner= rhs.m_bOwner; rhs.m_bOwner = false; } return *this; } // 代入をもういっちょ定義しとくか〜^^ auto_array<T>& operator=(const T* _P) { // 右辺値はポインタであって、その所有者については判らない if (m_lp != _P) { clear(); SetOwner(false); // よって、所有権は無いものとする m_lp = _P; } return *this; } virtual ~auto_array(){ clear(); } T* get(int n=0) const { // n番目の要素位置を返す return &m_lp[n]; } T* release() { T* tmp = m_lp; m_lp = NULL; m_bOwner = false; // 所有権の解放 return tmp; } // こういうのはあまり実装すべきでないが、 // 一応T*とコンパチビリティを保ちたい。 operator T* () const { return m_lp; } ///////////////////////////////////////////////////////////////// // あとは、auto_arrayオリジナル // std::vectorに準拠しておくほうが洗練された構文セットだろう void clear(){ // バッファ自体の解放 if (m_lp!=NULL && m_bOwner){ delete [] m_lp; m_bOwner = false; } m_lp = NULL; } void Add(const T* _P){ clear(); m_lp = const_cast<T*>(_P); SetOwner(true); } // インスタンスの生成追加構文 void resize(int n){ *this = auto_array<T>(new T[n]); } // サイズ指定によるコンストラクト(いちいち引数で(new T[n])なんて書くのはダサイ!) auto_array(int n){ m_lp = new T[n]; m_bOwner= true; } private: T* m_lp; // 配列の先頭を示すポインタ bool m_bOwner; // このポインタの所有者? }; #endif |