0

EX_BAD_ACCESS在调用vector.empty一个空向量时得到一个。

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
4

2 回答 2

2

正如@microtherion 所说,元素很可能是无效对象。这可能发生的一种简单方法:

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

或者通过返回一个向量引用,它是一个临时对象,并在函数结束时超出范围时死亡:

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;
}
于 2013-05-13T18:57:50.017 回答
1

最可能的原因是那个elements时候是一个无效的对象。对于有效的矢量对象,您永远不应获得此异常。

于 2013-05-13T00:12:47.970 回答