![](/img/trans.png)
[英]When do I need to delete pointers, and when do I need to set them to 0?
[英]Do i need to delete objects that i set in class member when i replace them?
我有以下幾點:
class Manager{
public:
void update(list<Employe> employees){
employees_ = employees;
}
private:
list<Employe> employees_;
};
我需要在更新方法的末尾刪除舊員工嗎?
沒有“老員工”。 在這種情況下
list<Employee>::operator = (const list<Employee> & source)
將被稱為。 如果未定義,則默認值會將將作為參數傳遞的實例的原始內容(員工)復制到字段(employees_)。
現在假設該列表包含一個指向動態分配內存的指針。 在這種情況下,對該內存的引用將丟失並且將泄漏。
正確的解決方案是檢查operator =是否正確重載(例如,所有標准容器已經實現了)還是自行實現(偽代碼):
void list<Employee>::operator = (const list<Employee> & source)
{
freeContents();
for (int i = 0; i < source.size(); i++)
add(source.getItem(i));
}
編輯:
如果列表實際上是std :: list,它將正確處理分配,因此在這種情況下,答案是:是的,列表本身將自動釋放。 但是,它的內容是另外一回事了。
在C ++中,賦值運算符將LHS復制到RHS,並負責銷毀當前占用LHS的所有內容。
在代碼中
void update(list<Employe> employees){
employees_ = employees;
}
函數執行后, employees_
的先前內容將被銷毀,並且employees_
現在將包含參數employees
的副本 。
為了提高效率,您可以刪除副本:
employees_ = std::move(employees); // C++11
要么
std::swap(employees_, employees); // C++03
在第一種情況下, employees_
的內容將被丟棄,而employees
的內容將被移至 employees_
,從而使employees
空。
在第二種情況下, employees_
和employees
的內容將被交換 ,因此當函數返回時, employees_
的原始內容將被丟棄。
不,您不會,它們將被自動銷毀。 因為它們存儲在自動存儲(堆棧)中
也有一點改進:
void update(const list<Employe> & employees){ //pass by reference, not by value
employees_ = employees; //old values are automatically destroyed and
// copies of new values are added, preserving the original values in passed container
}
在C ++ 11中,建議您將std::move
用作:
void update(list<Employee> employees) //NOTE : pass by value
{
employees_ = std::move(employees);
}
請注意,參數是通過值傳遞的,而不是通過引用傳遞的。 這意味着,當您編寫此代碼時,
update({e1,e2,e3,e3});
然后將從參數創建的臨時列表移至成員變量。 這樣,您可以避免制作臨時對象的副本(無論如何該副本都會被銷毀)。
如果使用list<Employee> const & employees
作為參數,則將無法std::move
通過上述調用創建的臨時對象的資源。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.