为什么没有 std::shared_ptr专业化?

发布于 2024-12-28 01:30:20 字数 486 浏览 1 评论 0 原文

该标准提供了 std::unique_ptr 的模板特化,它可以从其析构函数中正确调用 delete[]

void func()
{
   std::unique_ptr< int[] > arr(new int[10]);

   .......
}

使用 std::shared_ptr 这种特化不可用,所以有必要 提供一个正确调用delete[]的删除器:

void func()
{
    // Usage
    shared_ptr array (new double [256], [](double* arr) { delete [] arr; } ); 

    ..............
}

这只是一个疏忽吗? (就像有一个 std::copy_if 一样)或者有什么原因吗?

The standard provides a template specialization of std::unique_ptr which correctly calls the delete[] from its destructor:

void func()
{
   std::unique_ptr< int[] > arr(new int[10]);

   .......
}

With std::shared_ptr this specialisation is not available, so it is necessary to
to provide a deleter which correctly calls delete[]:

void func()
{
    // Usage
    shared_ptr array (new double [256], [](double* arr) { delete [] arr; } ); 

    ..............
}

Is this simply an oversight? (in the same way that there is an std::copy_if) or is there a reason?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

旧瑾黎汐 2025-01-04 01:30:20

LWG(C++ 委员会的库工作组)简要考虑了这种可能性,但这个想法并非没有争议。尽管争议主要是关于 shared_ptr 提案中添加的一个可能被放弃的功能(基于 shared_ptr 的算术)。

但最终真正的原因是,尽管进行了讨论,但 LWG 从未收到过执行此操作的实际书面提案。它从来没有充分地列出任何人的优先级列表(包括我自己的)以投入时间来编写提案。

最近,一些 LWG 成员之间重新开始了关于这个话题的非正式对话,我亲自制作了它的原型。但目前还没有书面提案。我认为这将是工具箱中一个不错的附加工具。这是否真的会发生,谁也说不准。

更新

shared_ptr的数组支持现在有一个草案TS:

http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4077.html

更新(2017)

这是现在 C++17 支持。请参阅 shared_ptr::shared_ptr()

The LWG (Library Working Group of the C++ committee) briefly considered the possibility but the idea wasn't without controversy. Though the controversy was mainly about a feature added to the shared_ptr<T[]> proposal that could have been jettisoned (arithmetic on shared_ptr<T[]>).

But ultimately the real real reason is that though it was discussed, there was never an actual written proposal in front of the LWG to do this. It never bubbled up anyone's priority list (including my own) sufficiently to put the time into writing a proposal.

Informal conversations have recently begun anew on this topic among a few LWG members, and I have personally prototyped it. But there is still no written proposal for it. I think it would be a decent additional tool in the toolbox. Whether it will ever actually happen or not is anyone's guess.

Update

Array support for shared_ptr now has a draft TS:

http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4077.html

Update (2017)

This is now supported in C++17. See case 3 of shared_ptr::shared_ptr()

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文