輸入優惠碼現折100元
首頁 / CompScience / Programming / Languages / C_and_CPP / Auto_ptr Pitfalls

Auto_ptr Pitfalls

C++ Primer 4/e在Exception Handling這個地方有一個警告:『The auto_ptr class template provides a measure of safety and convenience for handling dynamically allocated memory. To use auto_ptr correctly, we must adhere to the restrictions that the class imposes:

  1. Do not use an auto_ptr to hold a pointer to a statically allocated object. Otherwise, when the auto_ptr itself is destroyed, it will attempt to delete a pointer to a nondynamically allocated object, resulting in undefined behavior.

  2. Never use two auto_ptrs to refer to the same object. One obvious way to make this mistake is to use the same pointer to initialize or to reset two different auto_ptr objects. A more subtle way to make this mistake would be to use the result from get on one auto_ptr to initialize or reset another.

  3. Do not use an auto_ptr to hold a pointer to a dynamically allocated array. When the auto_ptr is destroyed, it frees only a single objectit uses the plain delete operator, not the array delete [] operator.

  4. Do not store an auto_ptr in a container. Containers require that the types they hold define copy and assignment to behave similarly to how those operations behave on the built-in types: After the copy (or assignment), the two objects must have the same value. auto_ptr does not meet this requirement.

中文版的這樣寫:『auto_ptr class template 為「管理動態配置記憶體」提供了一個安全方便的方法。欲正確使用auto_ptr,我們必須遵守它所要求的條件:

  1. 不要使用auto_ptr保存「指向靜態配置物」的指標。否則當這個auto_ptr被銷毀,它會嘗試刪除一個非動態配置物,導致不明確結果。
  2. 絕對不要令兩個auto_ptr指向同一個物件。明顯犯此錯誤的一種方式是,以同一個指標初始化或reset()兩個不同的auto_ptr物件。另一個犯此錯誤的隱微方式是,以「auto_ptr物件的get()的返回值」初始化或reset()另一個auto_ptr物件。
  3. 不要以auto_ptr物件保存動態配置的array。當這個auto_ptr物件被銷毀,它只會釋放一個物件。是的,它僅僅使用delete而不使用delete[]。
  4. 不要將auto_ptr物件保存於容器,因為容器要求其所保存的物件的型別的複製和賦值運算,必須與內建型別的對應運算行為一致:複製或賦值後左右兩物件必須有相同的內容。但auto_ptr無法滿足這一需求。

嗯,收錄起來!

Print Friendly, PDF & Email
馬上成為工作達人的Fans

About ㄚ琪

工作達人Fun Taiwan的創辦者及總編,可以在這裡更認識他。

發表迴響

你的電子郵件位址並不會被公開。 Required fields are marked *

*

這個網站採用 Akismet 服務減少垃圾留言。進一步瞭解 Akismet 如何處理網站訪客的留言資料

Scroll To Top