c++ - 分配未初始化的迭代器时发生访问冲突

标签 c++ visual-studio-2010

我在将未初始化的迭代器分配给已初始化的迭代器时遇到问题。以下代码摘录在使用 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/

相关文章:

c++ - 如何在 Visual C++ 2008 中显示命令行构建选项?

c++ - mkChar 不转义百分号

c++ - g++ ifstream 的类型不完整,存在正确的头文件

c# - VS 2010 "Go to Top of Page"快捷方式

visual-studio-2010 - MSBuild:将单个警告视为错误

c# - 在C#中保存文本文件

c# - 如何通过单击按钮动态生成图片框?

c# - 使用 Visual Studio 2010 编译时,覆盖泛型迭代器会导致 BadImageFormatException

c++ - map 中的 vector

c++ - 对于 { A=a;乙=乙; }, "A=a"会在 "B=b"之前严格执行吗?