给下面的容器添加几个拷贝构造函数和赋值函数:
template<typename T, size_t size> class fixed_vector { public: typedef T* iterator; typedef const T* const_iterator; iterator begin() { return v_; } iterator end() { return v_+size; } const_iterator begin() const { return v_; } const_iterator end() const { return v_+size; } private: T v_[size]; };
比较好的实现:
template<typename T, size_t size> class fixed_vector { public: typedef T* iterator; typedef const T* const_iterator; iterator begin() { return v_; } iterator end() { return v_+size; } const_iterator begin() const { return v_; } const_iterator end() const { return v_+size; } fixed_vector(); fixed_vector(const fixed_vector& fv); // more flexible copy ctor template<typename OT, size_t osize> fixed_vector(const fixed_vector<OT, osize>& fv) { if (this == &fv) return; copy(fv.begin(), fv.begin() + min(size, osize), begin()); } fixed_vector& operator = (const fixed_vector& fv); // more flexible copy assignment template<typename OT, size_t osize> fixed_vector<T, size>& operator = (const fixed_vector<OT, osize>& fv) { if ((void*)this != (void*)&fv) { copy(fv.begin(), fv.begin() + min(size, osize), begin()); } return *this; } private: T v_[size]; }; /** copy ctor */ template<typename T, size_t size> fixed_vector<T, size>::fixed_vector(const fixed_vector<T, size>& fv) { if (this == &fv) return; copy(fv.begin(), fv.end(), begin()); } /** default ctor */ template<typename T, size_t size> fixed_vector<T, size>::fixed_vector() { } /** copy assignment */ template<typename T, size_t size> fixed_vector<T, size>& fixed_vector<T, size>::operator = (const fixed_vector<T, size>& fv) { if (this != &fv) { copy(fv.begin(), fv.end(), begin()); } return *this; }
要想让容器保证有较高的异常安全级别:
template<typename T, size_t size> class fixed_vector { public: typedef T* iterator; typedef const T* const_iterator; fixed_vector() : v_( new T[size] ) { } ~fixed_vector() { delete[] v_; } // 能保证较高的异常安全 template<typename O, size_t osize> fixed_vector( const fixed_vector<O, osize>& other ) : v_( new T[size] ) { try { copy(other.begin(), other.begin() + min(size, osize), begin()); } catch(...) { delete[] v_; throw; } } // 能保证较高的异常安全 fixed_vector( const fixed_vector<T, size>& other ) : v_( new T[size] ) { try { copy(other.begin(), other.end(), begin()); } catch(...) { delete[] v_; throw; } } void Swap( fixed_vector<T, size>& other ) throw() { swap( v_, other.v_ ); } // 能保证较高的异常安全 template<typename O, size_t osize> fixed_vector<T, size>& operator=( const fixed_vector<O, osize>& other ) { fixed_vector<T, size> temp( other ); // does all the work Swap( temp ); // this can't throw return *this; } // 能保证较高的异常安全 fixed_vector<T, size>& operator=( const fixed_vector<T, size>& other ) { fixed_vector<T, size> temp( other ); // does all the work Swap( temp ); // this can't throw return *this; } iterator begin() { return v_; } iterator end() { return v_+size; } const_iterator begin() const { return v_; } const_iterator end() const { return v_+size; } private: T* v_; // 不能用原来数组的方式 };