(譯+原)std::shared_ptr及std::unique_ptr使用數組


轉載請注明出處:

http://www.cnblogs.com/darkknightzh/p/5462363.html

參考網址:

http://stackoverflow.com/questions/13061979/shared-ptr-to-an-array-should-it-be-used

 

默認情況下,std::shared_ptr會調用delete來清空內存。當使用new[] 分配內存時,需要調用delete[] 來釋放內存,否則會有內存泄露。

 

可以通過以下代碼來自定義釋放內存的函數:

1 template< typename T >
2 struct array_deleter
3 {
4     void operator ()(T const * p)
5     {
6         delete[] p;
7     }
8 };

通過以下代碼來聲明std::shared_ptr指針:

std::shared_ptr<int> sp(new int[10], array_deleter<int>());

此時,shared_ptr可正確的調用delete[]。

 

在C++11中,可以使用 std::default_delete代替上面自己寫的array_deleter:

std::shared_ptr<int> sp(new int[10], std::default_delete<int[]>());

 

也可以使用一下的lambda表達式來自定義刪除函數

std::shared_ptr<int> sp(new int[10], [](int *p) { delete[] p; });

 

實際上,除非需要共享目標,否則unique_ptr更適合使用數組:

std::unique_ptr<int[]> up(new int[10]); // this will correctly call delete[]

 

ps,上面代碼可以正確的分配空間,但是空間內的值都沒有初始化。如果需要默認初始化為0,可以使用下面的代碼:

std::unique_ptr<int[]> up(new int[10]()); // this will correctly call delete[]  初始化為0

 

ps2,使用vector時,可以通過fill函數來將vector中所有元素置為默認值。

vector<unsigned char> data(dataLen);
std::fill(data.begin(), data.end(), 0);

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM