【问题标题】:Design Behavior of auto_ptr, unique_ptr and shared_ptr for arrays数组的 auto_ptr、unique_ptr 和 shared_ptr 的设计行为
【发布时间】:2013-05-11 13:30:19
【问题描述】:

在了解 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]);

无论如何 auto_ptr 在 c++11 中已被弃用。而且我知道 unique_ptr 的功能比 auto_ptr 多得多。 我有两个与此行为有关的问题

a) 为什么 c++ 标准库团队在为 auto_ptr 设计行为时没有考虑到它对数组的不利影响。

b) 即使在 c++11 中引入了 shared_ptr,为什么它的实现不支持删除数组?

【问题讨论】:

标签: c++ c++11


【解决方案1】:

为什么 c++ 标准库团队在为 auto_ptr 设计行为时没有考虑到它对数组的不利影响。

我无法评论为什么auto_ptr 设计得不是很好;我只能观察到它不是,这就是它现在被弃用的原因。这真的不值得担心;假装它从未存在过。

还有即使在c++11中引入了shared_ptr,为什么它的实现不支持删除数组?

它支持任意删除器,所以你可以这样做;只是比unique_ptr 更不方便:

std::shared_ptr<int> p(new int[42], std::default_delete<int[]>());

【讨论】:

    【解决方案2】:

    这里是关于 auto_ptr 折磨历史的好书:http://www.aristeia.com/BookErrata/auto_ptr-update.html。事实是,在右值引用被发明之前,为标准容器设计具有异常安全性的防弹智能指针几乎没有希望。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-04-17
      • 2021-01-17
      • 1970-01-01
      • 1970-01-01
      • 2023-03-06
      • 1970-01-01
      • 2021-08-28
      • 2019-02-07
      相关资源
      最近更新 更多