0
在遍歷指針的STL ::向量時,沿途刪除對象的最佳做法是什麼?在迭代時刪除指針向量的最佳做法
我明白刪除成語。但是由於矢量包含指針,我擔心這隻會刪除指針,但將實例留在內存中。
例如,我會做類似
std::vector<someClass*> someClassList
std::vector<someClass*>::iterator i;
for (i=someClassList.begin(); i != someClassList.end(); ++i){
determine_if_should_be_deleted(i);
// <--How to delete the object and remove it from the vector without
// <--messing up the iterator?
}
在這裏不可能使用智能指針嗎? – risingDarkness
與'std :: vector>',你可以簡單地使用erase-remove idiom。 –
Jarod42
僅在STL容器中使用* non-owning *原始指針,即,如果將它們用作參考。如果容器需要擁有資源,請使用智能指針(auto_ptr除外)或[Boost的指針容器]之一(http://www.boost.org/doc/libs/release/libs/ptr_container/doc/ptr_vector的.html)。 –