在C ++中使用智能指针来动态分配数组(Using smart pointers for dynamically allocated arrays in C++)

编程入门 行业动态 更新时间:2024-10-11 21:28:56
在C ++中使用智能指针来动态分配数组(Using smart pointers for dynamically allocated arrays in C++)

根据Scott Meyers的Effective C ++的“第16项:使用new和delete相应形式”,你不应该把动态分配的数组放在auto_ptr (或tr1::shared_ptr )中,因为delete p而不是delete[] p被要求销毁(也见答案 )。 但是,这仍然适用于C ++ 11 <以及更多,特别是对于std::shared_ptr和std::unique_ptr ,因为我在一些开源代码中注意到使用std::unique_ptr<uint8_t[]> ? 如果后者是正确的,那么如何区分new和new []分配的数据?

Based on "Item 16: Use the same form in corresponding uses of new and delete" of Scott Meyers' Effective C++, you should not put dynamically allocated arrays in auto_ptr (or tr1::shared_ptr) since delete p instead of delete[] p is called upon destruction (also see answers). But does this still holds for C++11< and more in particular for std::shared_ptr and std::unique_ptr, since I noticed in some open source code the use of std::unique_ptr<uint8_t[]>? And if the latter is correct, how could one distinguish between new and new [] allocated data?

最满意答案

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 [] 。

`

std::unique_ptr is specialized for array types in C++11 where as it is not for std::shared_ptr. So std::unique_ptr<uint8_t[]> will call delete [] but std::shared_ptr<uint8_t[]> will just call delete by default.

This behavior has changed though in C++17. In C++17 std::shared_ptr has been specialized for array types and using std::shared_ptr<uint8_t[]> will call delete [].

`

更多推荐

本文发布于:2023-07-30 15:59:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1338844.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   指针   智能   动态分配   smart

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!