在了解auto_ptr、unique_ptr和shared_ptr时,我开始知道auto_ptr析构函数使用delete,而不是delete[],而unique_ptr确实可以正确处理它。
auto_ptr<char> aptr(new char[100]);
unique_ptr<char []> uptr(new char[100]);
Run Code Online (Sandbox Code Playgroud)
无论如何,auto_ptr 在 c++11 中已被弃用。而且我知道 unique_ptr 比 auto_ptr 具有更多功能。我有两个与此行为相关的问题
a) 为什么c++标准库团队在设计auto_ptr的行为时没有考虑到它对数组的缺点。
b) 另外,即使c++11中引入了shared_ptr,为什么它的实现不支持删除数组?
为什么c++标准库团队在设计auto_ptr的行为时没有考虑它对数组的缺点。
我无法评论为什么auto_ptr
设计得不是很好;我只能观察到事实并非如此,这就是为什么它现在已被弃用。这其实并不值得担心;假装它从未存在过。
另外,即使c++11中引入了shared_ptr,为什么它的实现不支持删除数组?
它支持任意删除器,所以你可以这样做;只是比使用稍微不太方便unique_ptr
:
std::shared_ptr<int> p(new int[42], std::default_delete<int[]>());
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
347 次 |
最近记录: |