我在将未初始化的迭代器分配给已初始化的迭代器时遇到问题。以下代码摘录在使用 Visual Studio 2010 构建时会产生访问冲突。在以前版本的 Visual Studio 中,代码应该可以正常工作。
#include <list>
int main() {
std::list<int> list;
std::list<int>::iterator it = list.begin();
std::list<int>::iterator jt;
it = jt; // crashes in VS 2010
}
这不会被认为是有效的 C++ 吗?
我需要这段代码来实现一个“游标”类,它要么指向任何地方,要么指向列表中的特定元素。如果我还没有对我的容器的引用,我还可以使用什么作为未初始化迭代器的值?
最佳答案
it = jt; // crashes in VS 2010
这会调用未定义的行为 (UB)。根据 C++ 标准,jt
是一个不与任何容器关联的单数迭代器,并且大多数表达式的结果对于单数迭代器是未定义的。
C++ 标准 (2003) 的第 24.1/5 节内容如下(具体请参阅粗体文本),
Just as a regular pointer to an array guarantees that there is a pointer value pointing past the last element of the array, so for any iterator type there is an iterator value that points past the last element of a corresponding container. These values are called past-the-end values. Values of an iterator i for which the expression *i is defined are called dereferenceable. The library never assumes that past-the-end values are dereferenceable. Iterators can also have singular values that are not associated with any container. [Example: After the declaration of an uninitialized pointer x (as with int* x;), x must always be assumed to have a singular value of a pointer.] Results of most expressions are undefined for singular values; the only exception is an assignment of a non-singular value to an iterator that holds a singular value. In this case the singular value is overwritten the same way as any other value. Dereferenceable values are always nonsingular.
如果MSVS2010崩溃了,这是UB的无限可能之一,因为UB意味着什么都有可能发生;该标准没有规定任何行为。
关于c++ - 分配未初始化的迭代器时发生访问冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8214116/