迭代器解除引用中的分段错误 [英] Segmentation fault in iterator dereferencing

查看:182
本文介绍了迭代器解除引用中的分段错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面列出的代码在基于迭代器的循环中触发了分段错误:

The code listed below triggers a segmentation fault in the iterator based loop:

#include <iostream>
#include <vector>

class A {
public:
    A(unsigned id = 0) {id_ = id;}
    unsigned get_id() {return id_;}
private:
    unsigned id_;
};

class B {
public:
    B() {}
    B(std::vector<A*> entries) : entries_(entries) {}
    const std::vector<A*> get_entries() const {
        return entries_;
    }
private:
    std::vector<A*> entries_;
};

int main() {
    std::vector<A*> entries;
    for (unsigned i = 0; i < 5; i++) {
        entries.push_back(new A(i));
    }
    B b(entries);

    // index based access (ok)
    for (unsigned i = 0; i < b.get_entries().size(); i++) {
        std::cout << b.get_entries()[i]->get_id() << std::endl;
    }

    // iterator based access (segmentation fault)
    for (std::vector<A*>::const_iterator i = b.get_entries().begin();
        i != b.get_entries().end();
        ++i) {
        std::cout << (*i)->get_id() << std::endl;
    }   
}

另一方面,基于索引的循环工作正常。

On the other hand, the index based loop works ok.

当返回 std :: vector 的副本时,会触发此行为(请参阅: const std :: vector< A *> get_entries()const )而不是 const 对它的引用,例如 const std :: vector< A *>& get_entries()const
后一种情况正常。

This behaviour is triggered when a copy of the std::vector is returned (see: const std::vector<A*> get_entries() const) and not a const reference to it, as e.g. const std::vector<A*>& get_entries() const. The latter case works fine.

如何解释这种行为?

推荐答案

get_entries()按值返回向量,您每个使用不同的 std :: vector< A *> 对象时间。比较来自不同向量的迭代器是Undefined Behavior,所以即使只有 get_entries()。begin()!= get_entries()。end()你已经遇到了麻烦。

Since get_entries() returns a vector by value, you're using a different std::vector<A*> object every time. Comparing iterators from different vectors is Undefined Behavior, so even with just get_entries().begin() != get_entries().end() you're already in trouble.

这篇关于迭代器解除引用中的分段错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆