有一種奇怪的用法,在你的代碼中向量中存儲新分配的對象。通常你應該以同樣的方式處理列表。因此,下面的示例將更加明確,並且彼此獨立,這應該有助於您理解差異。
僅將對象用於delete
。見下面的代碼。
僅針對「本機」數組使用delete []
,不適用於向量或類似的容器類或其中的對象。
雖然我不會給出數組的示例,因爲數組可能會更混亂。
默認例如堆棧:
vector <ItemClass> items(10);
// does not need to be deleted because item is on the stack
ItemClass item("device1", "10");
items.push_back(item);
默認例如用堆分配:
vector <ItemClass*> items(10);
ItemClass* pItem = new ItemClass("device2", "20");
items.push_back(pItem);
// delete all items inside vector
for (int i = 0; i < items.size(); i++)
{
ItemClass* pToDelete = items[i];
delete pToDelete;
items.erase(i);
}
以下實施例應避免與僅用於澄清的事情了!風險自負。
存儲堆棧變量地址:
vector <ItemClass*> items(10);
// does not need to be deleted because item is on the stack
ItemClass item("device3", "30");
items.push_back(&item); // storing a reference to item
// No need to delete this item that points to something on the stack.
// However you might not be able to tell items apart which have been
// created on the heap or the stack, so just dont do it.
如果混合了之前和存儲引用和指針,必須自己處理的例子。我的建議:不要這樣做。
存儲復引用的項目:
vector <ItemClass> items(10);
ItemClass* pItem = new ItemClass("device4", "40");
items.push_back(*pItem);
// must be deleted because allocated on the heap
// Again you can not tell which item is allocated on stack or heap. Avoid this.
謝謝澄清! – Yesman 2012-03-04 08:17:09