简体   繁体   English

std::advance 在 std::list 末尾的行为

[英]The behavior of std::advance at the end of std::list

#include <iostream>
#include <list>
using namespace std;

int main() {
  list<int> A;
  A.push_back(1);
  A.push_back(2);
  A.push_back(3);

  auto it = A.begin();
  cout << *it << ' ';
  advance(it, 1);
  cout << *it << ' ';
  advance(it, 1);
  cout << *it << ' ';
  advance(it, 1);
  cout << *it << ' ';
  advance(it, 1);
  cout << *it << ' ';
}

I belive that list is a double linked list.我相信该list是一个双向链表。 Surprisingly, the output is 1 2 3 3 1 .令人惊讶的是,output 是1 2 3 3 1 Can someone explain what's happening here?有人可以解释这里发生了什么吗? Here are questions:以下是问题:

  1. When we advance twice, we are at the node with 3 .当我们前进两次时,我们处于3的节点。 Here, an additional advance moves the iterator to A.end() .在这里,一个额外的advance将迭代器移动到A.end() I believe that A.end() is an imaginary node that does not point to the original element.我相信A.end()是一个不指向原始元素的虚构节点。 However, it prints out 3 .但是,它打印出3 Why?为什么?
  2. How come it prints out 1 at the end?怎么最后打印出1呢? The list is not a circular queue.list不是循环队列。

Dereferencing the end iterator is undefined.取消引用结束迭代器是未定义的。 The end iterator points one past the last element in the list.结束迭代器指向列表中的最后一个元素。 It does not not refer to an element in the list, because there is no element past the last.它不引用列表中的元素,因为没有元素超过最后一个。

Advancing the end iterator further is undefined as well.进一步推进结束迭代器也是未定义的。

Your program has undefined behavior.您的程序有未定义的行为。

Undefined behavior means anything can happen.未定义的行为意味着任何事情都可能发生。 The runtime behavior of code without undefined behavior is specified in the langauge standard (some is implementation defined or unspecified, but lets keep it simple).没有未定义行为的代码的运行时行为在语言标准中指定(有些是实现定义的或未指定的,但让我们保持简单)。 On the other hand, when your code has undefined behavior then you get no guarantee what the resulting program runtime behavior will be.另一方面,当您的代码具有未定义的行为时,您无法保证最终的程序运行时行为是什么。 Your output could be "Hello World" .您的 output 可能是"Hello World"

Of course the output is not "Hello World" and there is a reason why you see the output you do see.当然,output 不是"Hello World" ,您看到 output 是有原因的。 Though, these reasons are not related to how C++ works.但是,这些原因与 C++ 的工作原理无关。 To understand why you get the output you get you would have to study the assembly generated by the compiler.要了解为什么会得到 output,您必须研究编译器生成的程序集。 Eventually to understand why the compiler did generate this assembly you would need to study implementation details of your compiler.最终要了解编译器为何生成此程序集,您需要研究编译器的实现细节。 However, if you want to learn about C++ then any of this is futile and all you need to know is that your code has undefined behavior.但是,如果您想了解 C++,那么这些都是徒劳的,您需要知道的是您的代码具有未定义的行为。

I tested the program and it crashed我测试了这个程序,它崩溃了

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM