2

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?

Community
  • 1
  • 1
Matthias
  • 4,481
  • 12
  • 45
  • 84

2 Answers2

4

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

`

NathanOliver
  • 171,901
  • 28
  • 288
  • 402
2

The latter is correct, unique_ptr works fine with arrays. It has template specialization for array types which invokes delete[]. Nevertheless, Scott Meyers in his Effective Modern C++ suggests to use std::array or std::vector instead of smart pointers on arrays.

  • He also suggests using `boost::scoped_array` and `boost::shared_array` ;) Can you provide a link to the template specialization for array types? – Matthias Apr 04 '17 at 12:23
  • 2
    @Matthias look at Richard Critten's comment, he provides link to cppreference. The template instantiation is in your libstdc++ code. – Alexander Lapenkov Apr 04 '17 at 12:27