【问题标题】:Why does dereferencing an iterator make output-stream cut out?为什么取消引用迭代器会切断输出流?
【发布时间】:2016-10-31 04:24:11
【问题描述】:

我正在练习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 的值。

我认为这是真正的原因,为什么...。

我的母语不是英语,如果您发现错误,请见谅

【问题讨论】:

  • 您不能取消引用结束迭代器。使用它是未定义的行为。
  • 如果要倒退,请使用 rbegin 和 rend(与使用 begin 和 end 相同)
  • 当你说你知道结束迭代器是空的,这听起来就像你期望它返回一个空字符串,这是完全错误的。
  • 我只是想说它不能给你一个例外,除非它知道。这将要求标准库在每次访问迭代器时花费额外的 cpu 和内存来检查迭代器。您问题的实际答案在第一条评论中。你搞砸了 "it=wup.end(); cout

标签: c++ iterator cout deque


【解决方案1】:

我哪里做错了?

这一行:

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

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

为什么在这种情况下,毫无例外地切断输出流?

这个问题分为两部分:

  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.  

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-17
    • 2015-01-13
    • 1970-01-01
    相关资源
    最近更新 更多