2013-05-12 45 views
0

在空向量上調用vector.empty時,我得到一個EX_BAD_ACCESSEX_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 

回答

1

最可能的原因是elements在這一點上是無效的對象。你永遠不應該得到這個有效的矢量對象的異常。

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; 
}