[英]EX_BAD_ACCESS when calling vector.empty()
I'm getting a EX_BAD_ACCESS
when calling vector.empty
on an empty vector. 我得到一个
EX_BAD_ACCESS
打电话时vector.empty
上的空载体。
bool empty = elements.empty();
Its throwing the exception here; 在这里抛出异常;
/**
* 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
when calling; 打电话时
/**
* Returns true if the %vector is empty. (Thus begin() would
* equal end().)
*/
bool
empty() const
{ return begin() == end(); } // EXCEPTION
As @microtherion stated, elements is most likely an invalid object. 如@microtherion所述,元素很可能是无效对象。 A simple way this this can happen:
发生这种情况的一种简单方法:
std::vector<MyType> *theElements = nullptr;
std::vector<MyType> &elements = *theElements;
bool empty = elements.empty();
Or by returning a vector reference that is a temporary object and dies when it goes out of scope at the end of the function: 或者返回一个作为临时对象的向量引用,当该引用超出函数范围时终止,该引用将死亡:
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();
}
Or by holding a reference to a member variable of another class that gets cleaned up before: 或通过持有对另一个要在此之前清除的类的成员变量的引用:
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;
}
The most likely reason for this is that elements
is an invalid object at that point. 造成这种情况的最可能原因是,此时
elements
是无效对象。 You should never get this exception for a valid vector object. 对于有效的矢量对象,永远不要获取此异常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.