Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Design Behavior of auto_ptr, unique_ptr and shared_ptr for arrays

Tags:

c++

c++11

while understanding about auto_ptr, unique_ptr and shared_ptr I came to know that auto_ptr destructor uses delete, not delete[] where as unique_ptr does handle it properly.

auto_ptr<char> aptr(new char[100]);
unique_ptr<char []> uptr(new char[100]);

Anyhow auto_ptr is deprecated in c++11.And I know unique_ptr has much more functionality than auto_ptr. I have two questions related to this behavior

a) Why while designing behavior for auto_ptr by c++ standard library team has not considered it's disadvantages for arrays.

b) Also even though shared_ptr introduced in c++11 why it's implementation doesn't support deleting of array?

like image 977
shivakumar Avatar asked Oct 23 '25 06:10

shivakumar


2 Answers

Why while designing behavior for auto_ptr by c++ standard library team has not considered it's disadvantages for arrays.

I can't comment on why auto_ptr wasn't very well designed; I can only observe that it wasn't, which is why it's now deprecated. It's not really worth worrying about; just pretend it never existed.

Also even though shared_ptr introduced in c++11 why it's implementation doesn't support deleting of array?

It supports arbitrary deleters, so you can do that; just slightly less conveniently than with unique_ptr:

std::shared_ptr<int> p(new int[42], std::default_delete<int[]>());
like image 54
Mike Seymour Avatar answered Oct 24 '25 20:10

Mike Seymour


Here is a good read on the tortured history of auto_ptr: http://www.aristeia.com/BookErrata/auto_ptr-update.html. The truth is, until rvalue references were invented, there was little hope of designing a bullet proof smart pointer with exception safety for standard containers.

like image 21
Scott Jones Avatar answered Oct 24 '25 21:10

Scott Jones



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!