为什么取消引用迭代器会切断输出流?

Why does dereferencing an iterator make output-stream cut out?

我正在练习 std::deque,特别是 迭代器

我测试了 end 迭代器。像这样:

    std::deque<const char*> wup {"how","are","you","doing","today?"};
    std::deque<const char*>::iterator it = wup.end();

然后,我想打印 it ,并且 我知道结束迭代器是空的。

然后我尝试使用2个cout语句来打印it的内容:一个在--it之前,另一个在--it

之后

但是如果我在--it之前写一个cout,最后的cout不会出现在输出中。

像这样:

std::deque<const char*> wup {"how","are","you","doing","today?"};
std::deque<const char*>::iterator it = wup.end();
std::cout<<"Before --it: "<<*it<<std::endl;// okay, it works good | and finishes console
--it;
std::cout<<"After --it: "<<*it<<std::endl;// I do not know why it does not appear.

输出:

    Before --it:
    Process returned 0 (0x0)   execution time : 0.010 s
    Press ENTER to continue.

我哪里弄错了?
如果取消引用迭代器是错误的...
为什么在这种情况下,毫无例外地切断输出流
非常感谢。 测试于:
OS: Ubuntu 16.01
compiler: g++ version: 5.3.1
IDE: code::blocks 16.01


编辑: 我在 /reference/en/cpp/container/map/erase.html 中找到了这个 note :

迭代器 pos 必须有效且可取消引用。因此 end() 迭代器(有效,但不是 dereferencable)不能用作 pos 的值。

I think this is real reason for, why ... .

我的母语不是英语,如有错误请见谅

Where did i make a mistake?

这一行:

std::cout<<"Before --it: "<<*it<<std::endl;

正在取消引用指向容器末尾的迭代器,这是未定义的行为。

Why this case, cuts the output-stream without any exception?

这个问题分为两部分:

  1. 为什么会截断输出流?因为未定义的行为是未定义的。你不知道会发生什么。有很多关于此的信息:http://en.cppreference.com/w/cpp/language/ub

  2. 为什么没有异常?为了对所有可能导致 UB 的情况提供例外,c++ 将不得不检查每个取消引用,这在计算上代价高昂,但收效甚微。是否正确使用迭代器接口取决于用户。这与以下示例相同:


 int a[5];
 a[6] = 10; // Why does c++ allow this when it is clearly a mistake? Because the user is 
            // responsible for writing good code, not the compiler, and certainly
            // not the run-time exception handler.