【发布时间】:2015-11-05 20:38:43
【问题描述】:
我已经为一个自定义库实现了一个 random_access_iterator(它被模板化为可作为 const 迭代器和非常量迭代器重用),但它在执行类似 std::sort(container.begin(), container.end() (container.begin()/end() return @987654323 @实例。
我的实现有什么问题?
template <bool is_const_iterator = false>
class meta_iterator : public std::iterator<std::random_access_iterator_tag, T> {
public:
typedef T value_type;
typedef std::ptrdiff_t difference_type;
typedef typename std::conditional<is_const_iterator, const value_type &,
value_type &> reference;
typedef std::random_access_iterator_tag iterator_category;
typedef typename std::conditional<is_const_iterator, value_type const *,
value_type *>::type pointer;
typedef meta_iterator self_type;
meta_iterator(T *ptr) : ptr_(ptr) {}
meta_iterator(const meta_iterator<true> &other) : ptr_(other.ptr_) {}
self_type operator+(difference_type value) {
ptr_ += value;
return *(this);
};
self_type operator-(difference_type value) {
ptr_ -= value;
return *(this);
};
difference_type operator-(const self_type &other) {
return ptr_ - other.ptr_;
}
T &operator[](difference_type value) const { return *ptr_[value]; }
bool operator==(const self_type &other) const { return ptr_ == other.ptr_; }
bool operator!=(const self_type &other) const { return !(*this == other); }
bool operator>=(const self_type &other) const { return !((*this) < other); }
bool operator<=(const self_type &other) const { return !((*this) > other); }
bool operator<(const self_type &other) const { return ptr_ < other.ptr_; }
bool operator>(const self_type &other) const { return ptr_ < other.ptr_; }
self_type &operator=(const self_type &other) {
ptr_ = other.ptr_;
return *(this);
}
T *operator->() const { return ptr_; }
T &operator*() const { return *ptr_; }
self_type &operator--() {
ptr_--;
return *this;
}
self_type operator--(int) {
self_type temp(*this);
--(*this);
return (temp);
}
self_type &operator++() {
ptr_++;
return *this;
}
self_type operator++(int) {
self_type temp(*this);
--(*this);
return (temp);
}
self_type &operator+=(difference_type value) {
ptr_ += value;
return *(this);
}
self_type &operator-=(difference_type value) {
ptr_ -= value;
return *(this);
}
friend class meta_iterator<true>;
friend class meta_iterator<false>;
private:
T *ptr_;
};
【问题讨论】:
-
你确定,内存泄漏是由这个迭代器引起的吗?如何判断内存泄漏?
-
您认为问题所在的原因是什么?可能 1) 容器泄漏 2) 容器中使用的类型执行不正确(任何规则..)
-
@cdonat 很好,应该是。 std::sort 根本不依赖于容器(假设
begin()和end()实现正确),所以我假设 AddressSanitizer 指向迭代器泄漏。
标签: c++ templates memory-leaks stl iterator