根据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 [].
`
更多推荐
发布评论