我已经实现了一个简单的矢量类结构如果我使用vector< int>它会很好用或矢量< char>但是当我使用< vector< vector< int>>它会造成错误有好的……
你的实现不遵循 规则3 ,因为它缺少一个复制构造函数,和 正确 复制赋值运算符(可以使用复制构造函数实现)。而在C ++ 11及更高版本中,规则为5,通过添加移动构造函数和移动赋值运算符。
此外,对于定义了构造函数/析构函数的非平凡类型(例如何时),您的实现无法正常工作 T 是另一个 _vector 类型,或在其中分配指针/资源的任何其他类型。因此,您的类需要在使用时向元素添加元素时构造新对象 placement-new ,通过直接调用它们的析构函数,从数组中删除元素时破坏对象。
T
_vector
placement-new
尝试更像这样的东西:
template <typename T> class _vector { public: typedef unsigned int size_type; typedef T value_type; private: size_type _size; size_type _capacity; value_type* vc; public: _vector(size_type initalcap = 0) : _size(0), _capacity(0), vc(0) { reserve(initialcap); } _vector(const _vector<T> &src) : _size(0), _capacity(0), vc(0) { reserve(src._capacity); for(size_type i = 0; i < src._size; ++i) { new(vc[i]) value_type(src.vc[i]); } _size = src._size; } // C++11 and later only... _vector(_vector<T> &&src) : _size(src._size), _capacity(src._capacity), vc(src._vc) { src._size = 0; src._capacity = 0; src.vc = 0; } ~_vector() { clear(); delete[] reinterpret_cast<char*>(vc); } size_type size() const { return _size; } size_type capacity() const { return _capacity; } bool empty() const { return !_size; } void reserve(size_type newcap) { if (newcap <= _capacity) return; value_type* tmp = reinterpret_cast<value_type*>(new char[sizeof(value_type) * newcap]); for (size_type i = 0; i < _size; ++i) { new(tmp[i]) value_type(vc[i]); } delete[] reinterpret_cast<char*>(vc); vc = tmp; _capacity = newcap; } void resize(size_type newsize) { if (newsize < _size) { for(size_type i = _size; i-- > newsize; ) { vc[i].~value_type(); } _size = newsize; } else if (newsize > _size) { reserve(newsize); for (size_type i = _size; i < newsize; ++i) { new(vc[i]) value_type(); } _size = newsize; } } void clear() { resize(0); } void push_back(const T &val) { if (_size == _capacity) reserve(2 * _capacity); new(vc[_size]) value_type(val); ++_size; } void pop_back() { if (_size) { vc[--_size].~value_type(); } } value_type& operator[](size_type i) { return vc[i]; } const value_type& operator[](size_type i) const { return vc[i]; } _vector<T>& operator=(const _vector<T> &rhs) { if (&rhs != this) { _vector<T> tmp(rhs); std::swap(tmp.vc, vc); std::swap(tmp._size, _size); std::swap(tmp._capacity, _capacity); } return *this; } // C++11 and later only... _vector<T>& operator=(_vector<T> &&rhs) { _vector<T> tmp(std::move(rhs)); std::swap(tmp.vc, vc); std::swap(tmp._size, _size); std::swap(tmp._capacity, _capacity); return *this; } };