2017-04-04 46 views
1

智能指針「第16項:使用相同的形式和new相應用途delete」斯科特邁爾斯有效的C++,你不應該把動態的auto_ptr(或tr1::shared_ptr)分配數組因爲delete p而不是delete[] p被銷燬(另請參閱answers)。但是,這仍然適用於C++ 11 <和更多,特別是std::shared_ptrstd::unique_ptr,因爲我注意到在一些開源代碼中使用了std::unique_ptr<uint8_t[]>?如果後者是正確的,那麼如何區分newnew []分配的數據?使用在C++基於動態分配數組

+0

使用'std :: vector'作爲數組(可能不是'bool',依賴)。它是C++中標準動態大小的數組。 –

+2

請參閱http://en.cppreference.com/w/cpp/memory/unique_ptr並查看點(2),它是註釋 –

回答

4

std::unique_ptr專門用於C++ 11中的數組類型,因爲它不適用於std::shared_ptr。所以std::unique_ptr<uint8_t[]>將會呼叫delete [],但std::shared_ptr<uint8_t[]>默認會調用delete

儘管在C++ 17中,此行爲已更改。在C++ 17中std::shared_ptr已經專門用於陣列類型,使用std::shared_ptr<uint8_t[]>將會調用delete []

`

2

後者是正確的,unique_ptr與陣列工作正常。它具有調用delete[]的數組類型的模板專門化。不過,Scott Meyers在他的Effective Modern C++中建議使用std::arraystd::vector而不是數組上的智能指針。

+0

他還建議使用'boost :: scoped_array'和'boost :: shared_array';)Can你提供了一個指向數組類型的模板專門化的鏈接? – Matthias

+2

@Matthias查看Richard Critten的評論,他提供了cppreference的鏈接。模板實例化在您的libstdC++代碼中。 –