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?

2
  • Use std::vector for arrays (of other than bool maybe, depends). It is the standard dynamically sized array in C++. Commented Apr 4, 2017 at 12:19
  • 2
    See en.cppreference.com/w/cpp/memory/unique_ptr and look at point (2) and it's notes Commented Apr 4, 2017 at 12:20

2 Answers 2

5

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

`

Sign up to request clarification or add additional context in comments.

Comments

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.

2 Comments

He also suggests using boost::scoped_array and boost::shared_array ;) Can you provide a link to the template specialization for array types?
@Matthias look at Richard Critten's comment, he provides link to cppreference. The template instantiation is in your libstdc++ code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.