(译+原)std::shared_ptr及std::unique_ptr使用数组
轉(zhuǎn)載請注明出處:
http://www.cnblogs.com/darkknightzh/p/5462363.html
參考網(wǎng)址:
http://stackoverflow.com/questions/13061979/shared-ptr-to-an-array-should-it-be-used
?
默認情況下,std::shared_ptr會調(diào)用delete來清空內(nèi)存。當使用new[] 分配內(nèi)存時,需要調(diào)用delete[] 來釋放內(nèi)存,否則會有內(nèi)存泄露。
?
可以通過以下代碼來自定義釋放內(nèi)存的函數(shù):
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可正確的調(diào)用delete[]。
?
在C++11中,可以使用?std::default_delete代替上面自己寫的array_deleter:
std::shared_ptr<int> sp(new int[10], std::default_delete<int[]>());?
也可以使用一下的lambda表達式來自定義刪除函數(shù)
std::shared_ptr<int> sp(new int[10], [](int *p) { delete[] p; });?
實際上,除非需要共享目標,否則unique_ptr更適合使用數(shù)組:
std::unique_ptr<int[]> up(new int[10]); // this will correctly call delete[]?
ps,上面代碼可以正確的分配空間,但是空間內(nèi)的值都沒有初始化。如果需要默認初始化為0,可以使用下面的代碼:
std::unique_ptr<int[]> up(new int[10]()); // this will correctly call delete[] 初始化為0?
ps2,使用vector時,可以通過fill函數(shù)來將vector中所有元素置為默認值。
vector<unsigned char> data(dataLen); std::fill(data.begin(), data.end(), 0);總結
以上是生活随笔為你收集整理的(译+原)std::shared_ptr及std::unique_ptr使用数组的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ST的IAP例程和手册里都说解除写保护需
- 下一篇: 【网络协议】TCP分段与UDP/IP分片