【发布时间】:2012-02-01 11:02:09
【问题描述】:
我正在做的一个项目的部分源代码,负责压缩一系列“事件”,如下所示:
#include <iterator>
#include <list>
typedef int Event;
typedef std::list<Event> EventList;
struct Compressor {
// Returns an iterator behind the last element which was 'eaten'
virtual EventList::const_iterator eatEvents( const EventList &l ) = 0;
};
// Plenty of Compressor subclasses exist
void compressAndCopyEatenEvents( Compressor &c ) {
EventList e;
e.push_back( 1 );
EventList::const_iterator newEnd = c.eatEvents( e );
EventList eatenEvents;
std::copy( e.begin(), newEnd, std::back_inserter( eatenEvents ) ); // barfs
}
这里的问题是compressAndCopyEatenEvents 函数有一个非常量的事件列表;此列表 os 传递给 eatEvents 方法,该方法采用对 const 的引用并产生 const_iterator。现在compressAndCopyEatenEvenst 函数想复制吃掉事件的范围,所以它决定使用一些算法(这里是std::copy,当然也可以用正确的std::list 构造函数调用来替换——重点是各种范围都存在这个问题)。
不幸的是(?)许多(如果不是全部?)范围需要由相同的迭代器类型组成。然而,在上面的代码中,'e.begin()' 产生一个 EventList::iterator(因为对象不是 const),而 'newEnd' 是一个 EventList::const_iterator。
这里是否存在导致这种混乱的设计缺陷?你会怎么处理呢?
【问题讨论】:
-
你需要非常量迭代器吗?如果没有,那么你应该让你的所有代码只使用 const 迭代器。
-
我猜
EventList::const_iterator begin = e.begin();传递它太多了?由于您的使用方法,我看不到任何方法...