迭代器取消引用中的分段错误

Segmentation fault in iterator dereferencing

本文关键字:分段 错误 取消 引用 迭代器      更新时间:2023-10-16

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

#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;
    }   
}

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

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

如何解释这种行为?

由于get_entries()按值返回向量,因此每次都使用不同的std::vector<A*>对象。比较不同向量的迭代器是Undefined Behavior,所以即使只有get_entries().begin() != get_entries().end(),您也已经遇到了麻烦。

问题是get_entries返回向量的临时副本,而不是对原始向量的引用。因此,每次你调用它并将迭代器获取到一个临时返回值时,该迭代器在你使用它时都将无效。这会导致未定义的行为,在这种行为中崩溃是很常见的。

这里有两个选项。

选项1:将返回的向量存储在局部变量中,并对其进行迭代。

选项2:修改函数以返回引用const std::vector<A*> & get_entries() const