您应该将此功能提取到一个单独的类中,并在场景中具有该类型的数据成员:
struct ImagePtrVector {
typedef Image *value_type;
typedef int size_type;
ImagePtrVector() : _begin (), _end (), _end_alloc () {}
~ImagePtrVector() {
for (value_type x = _begin; x != _end; ++x) {
delete *x;
}
delete[] _begin;
}
// Either define these two yourself or mark private:
ImagePtrVector(ImagePtrVector const &x);
ImagePtrVector& operator=(ImagePtrVector const &x);
value_type& operator[](size_type index) {
assert(0 <= index); // Or other checking as you like.
assert(index < size());
return _begin[index];
}
value_type const& operator[](size_type index) const {
assert(0 <= index); // Or other checking as you like.
assert(index < size());
return _begin[index];
}
size_type size() const { return _end - _begin; }
size_type capacity() const { return _end_alloc - _begin; }
void reserve(size_type capacity) {
if (this->capacity() < capacity) {
value_type *new_begin = new value_type[capacity];
// Exception-safe only because I know the below won t throw.
std::copy(_begin, _end, new_begin);
_end_alloc = new_begin + capacity;
_end = new_begin + this->size();
delete[] _begin;
_begin = new_begin;
}
}
void resize(size_type size) {
reserve(size);
for (size_type diff = size - this->size(); diff > 0; --diff) {
*_end++ = new Image();
}
}
// Add push_back, begin/end, etc. to taste.
private:
value_type *_begin, *_end, *_end_alloc;
};
std::vector和boost::ptr_vector的区别并非巧合,您应该评估是否真的需要编写一个特殊的容器,或者是否可以重用现有的通用容器。