EX_BAD_ACCESS when calling vector.empty()
EX_BAD_ACCESS when calling vector.empty()
在一个空向量上调用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对象,永远不应该出现此异常。
相关文章:
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- 在c++中用vector填充一个简单的动态数组
- vector.resize()中的分配错误
- 使用std::vector的OpenCL矩阵乘法
- POCO::PostgreSQL:如何将std::vector支持添加到`Binder::bind`
- 在某些循环内使用vector.push_back时出现分段错误
- 当vector是tje全局变量时,c++中vector的内存管理
- std::vector的包装器,使数组的结构看起来像结构的数组
- 为什么(-1)%vector::size()总是返回0
- 在从 std::vector 移动的上调用 .clear()、.shrink_to_fit()、.empty() 是否合
- vector.size()= 0和vector.empty()之间是否有区别
- std::find on empty vector 是否会导致未定义的行为
- vector::empty()出错,或者我遗漏了什么
- 调用std::vector::empty()时内存访问冲突读取位置
- Matlab's is empty for a std::vector ( C++)
- empty deque vs vector
- Empty std::vector begin != end
- 更有效的是:vector.clear()或if(vector.empty())clear();
- EX_BAD_ACCESS when calling vector.empty()
- Vector is returned empty