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 に答える