为什么没有 std::shared_ptr专业化?
该标准提供了 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 一样)或者有什么原因吗?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
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 onshared_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()