EX_BAD_ACCESS when calling vector.empty()

EX_BAD_ACCESS when calling vector.empty()

本文关键字:empty vector when BAD ACCESS EX calling      更新时间:2023-10-16

在一个空向量上调用vector.empty时,我得到一个EX_BAD_ACCESS

bool empty = elements.empty();

这里抛出了异常;

      /**
       *  Returns a read-only (constant) iterator that points one past
       *  the last element in the %vector.  Iteration is done in
       *  ordinary element order.
       */
      const_iterator
      end() const
      { return const_iterator(this->_M_impl._M_finish); } // EXCEPTION

当调用;

  /**
   *  Returns true if the %vector is empty.  (Thus begin() would
   *  equal end().)
   */
  bool
  empty() const
  { return begin() == end(); } // EXCEPTION

如@microtherion所述,elements很可能是一个无效对象。有一种简单的方法:

std::vector<MyType> *theElements = nullptr;
std::vector<MyType> &elements = *theElements;
bool empty = elements.empty();

或者返回一个临时对象的vector引用,当它在函数结束时超出作用域时死亡:

std::vector<MyType>& GetElements() {
  std::vector<MyType> temporaryElements;
  //add to vector here.
  return temporaryElements;
}
void foo() {
  std::vector<MyType> &elements = GetElements();
  bool empty = elements.empty();
}

或者保存对另一个类的成员变量的引用,该类在此之前已被清理:

class Foo {
  private: std::vector<MyType> mElements;
  public: std::vector<MyType>& GetElements();
};
class Bar {
private:
  std::vector<MyType>& elements;
public:
  Bar(Foo& foo) : elements(foo.GetElements()) { }
  void Do(void) { bool empty = elements.empty(); }
};
//Probably much more hidden between multiple function calls, rather than this clear example.
void func(void) {
  Bar* bar = nullptr;
  {
    Foo foo;
    bar = new Bar(foo);
    //foo dies, and so does the elements vector bar.elements refers to.
  }
  bar->Do();
  delete bar;
}

最可能的原因是elements在那一点上是一个无效的对象。对于有效的vector对象,永远不应该出现此异常。