2010-04-01 30 views

回答

2

由於您正在創建新玩家(),您將不得不刪除它們。可能最好通過刪除玩家的向量迭代,然後清理你的向量。

8

如果你需要存儲的指針的東西在一個容器中,您應該保存某種形式的智能指針(如std::tr1::shared_ptrboost::shared_ptr),或使用專門用於存儲指針,就像那些在Boost Pointer Container Library找到的容器。

如果您存儲裸指針,則需要記住在容器銷燬之前刪除容器中的指針。這包括任何時候拋出可能導致容器被銷燬的異常。考慮到前一段提到的設施,正確地做這件事很麻煩,容易出錯,而且完全沒有必要。

+1

+1 for ptr_container – vladr 2010-04-01 04:48:30

+0

值得一提的是,用'C++ 0x'來得到適合這種任務的'unique_ptr'。用'shared_ptr'開銷要低得多。 – 2010-04-01 06:26:24

3

是的,你自己需要delete他們。該向量只會「破壞」指針(它什麼都不做)。

如果可以,請使用Boost pointer containers library,您不必擔心。但是,如果你不能需要將容器包裝起來。考慮在容器被填充的時間和其元素被刪除的時間之間拋出異常。您將不是執行元素刪除代碼並泄漏。

一個簡單的包裝看起來像:

struct default_deleter 
{ 
    template <typename T> 
    void operator()(T* pPtr) 
    { 
     delete pPtr; 
    } 

}; 

template <typename T, typename Deleter = default_deleter> 
struct container_wrapper 
{ 
    typedef T container_type; 
    typedef Deleter deleter_type; 

    container_wrapper(container_type pContainer = container_type()) : 
    container(pContainer) 
    {} 

    ~container_wrapper(void) 
    { 
     std::for_each(container.begin(), container.end(), deleter_type()); 
    } 

    container_type container; 
}; 

這樣使用它:

typedef std::vector<int*> vec_intptr; 
typedef container_wrapper<vec_intptr> vec; 

vec v; 
v.container.push_back(new int); // and never worry about it again 

這是一個簡單的包裝。任何pop_back()erase()等操作都會產生錯誤的效果。我強烈建議使用Boost。

有人可能會想到使用auto_ptr的容器。相反,這是一個壞主意; auto_ptr的複製語義阻止它的工作。如果可能的話,最好的選擇是擺脫動態分配。

+0

我不知道我們是否可以在矢量中使用自動指針。 http://www.gotw.ca/publications/using_auto_ptr_effectively.htm – 2010-04-01 04:42:39

+0

@Sammy,不能在STL容器中使用'auto_ptr'。 **可以**使用boost指針容器lib。 – vladr 2010-04-01 04:45:33

+0

@GMan,最後一個'container_wrapper'聲明可能會引起誤解;如果OP決定調用'v.container.erase','v.container.clear'等,OP仍然需要擔心。 – vladr 2010-04-01 04:47:58