C ++ rend()指向与rbegin()相同的元素

时间:2016-08-16 21:26:27

标签: c++ iterator segmentation-fault

运行下面的代码,我希望看到测试1的第4个值的不同地址(与值1和3不同)。这表明rend()与rbegin()相同? 我也不希望循环经历第二次迭代并获得段错误。

知道我做错了吗?

test 1:
0x2299050
0x7fffcd574908
0x2299050
0x2299050
test 2:
next iteration
next iteration
*** glibc detected *** ./foo: double free or corruption (fasttop): 0x0000000002299030 ***

输出:

map<int, int> newMap;
newMap[13] = 1340;
cout << "test 2:" << endl;
for(map<int, int>::reverse_iterator it=newMap.rbegin();it!=newMap.rend();){
  cout << "next iteration" << endl;
  int index = it->first;
  int value = it->second;
  it++;
  newMap.erase(index);
}

编辑:这是一个更新/简化的版本,仍然存在同样的问题(仅限测试2);这不会导致段错误,因为它不使用指针,但仍然会循环两次:

@Configuration
public abstract class ParentConfig {
    public ComplexBean complexBean() {
        return new ComplexBeanImpl(templateBean(), bean2(), bean3(),...);
    }

    public abstract TemplateBean templateBean();
}

@Configuration
public class Child_1Config extends ParentConfig {
    @Bean
    public ComplexBean complexBean_1() {
        return super().complexBean();
    }

    @Override
    public TemplateBean templateBean() {
        return new TemplateBeanImpl_1();
    }
}

1 个答案:

答案 0 :(得分:0)

在测试1中,您将取消引用过去的迭代器。正如ArchbishopOfBanterbury在评论中提到的那样,结果尚未定义。

在测试2中,您通过删除__init__.py指向的元素使it无效。 std::reverse_iterator包含下一个元素的迭代器(因此it.base()保持迭代器等于newMap.rbegin()newMap.end()保持迭代器等于newMap.rend())。

当您增加newMap.begin()时,它会等于it,这意味着newMap.rend()等于it.base()。然后删除newMap.begin()引用的元素,这会使it.base()无效,从而使it.base()无效。由于it现在无效,因此将其与it进行比较并不起作用。