有“3”种方法可以从索引中访问项目QList
:
const T& QList::at(int) const
T& QList::operator[](int)
const T& QList::operator[](int) const
如果您查看文档,您会发现最后一个很简单:
与 at() 相同。该函数以恒定时间运行。
So we are left with the first one (at
) and the non-const operator[]
. Here is the problem, the documentation of the second one tells you that1:
如果在当前正在共享的列表上调用此函数,它将触发所有元素的副本。否则,该函数将在恒定时间内运行。如果您不想修改列表,您应该使用QList::at()
.
Note:这也适用于QVector
:
请注意,使用非常量运算符可能会导致QVector
进行深复制。
1 For QList
, this is actually only true for Qt 5 http://doc.qt.io/qt-5/qlist.html#operator-5b-5d, not for Qt 4 http://doc.qt.io/qt-4.8/qlist.html#operator-5b-5d (at least in the documentation), but for QVector
it was already true for Qt 4 http://doc.qt.io/qt-4.8/qvector.html#operator-5b-5d, so the .at
method was probably made consistent between all Qt containers.
这意味着您不能使用operator[]
直接在非常量共享上QList
或非常量QVector
,你需要做类似的事情:
QList<T> &mySharedQList = ...;
const QList<T> &myConstRef = mySharedQList;
myConstRef[0]; // Only ways not to copy the original QList
我的猜测是,这样做的目的是.at
就是为你提供一个方法保证恒定的访问时间,无论什么QList
or QVector
是(其中operator[]
不保证)。对于标准库容器,您不需要这样的方法,因为非常量operator[]
已经保证在恒定时间内运行(它们永远不会复制)。
关于对索引的检查,这可能是为了保持operator[]
因为,不像std::vector
,你可能想使用.at
任何地方你只需要读取数据。