繁体   English   中英

为什么取消对迭代器的引用会使输出流中断?

[英]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中找到了此注释

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

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

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

我在哪里弄错了?

这行:

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

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

为什么这种情况会毫无例外地削减输出流?

这个问题分为2部分:

  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.  

暂无
暂无

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

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