I never understood why std::shared_ptr
and std::unique_ptr
differ when used with arrays, i.e. why do I have to explicitly specify the deleter for std::shared_ptr
? I know I have to do it, I don't understand why it was designed like this.
For example, for an array of type class Foo{...};
, using a std::unique_ptr
is straightforward:
std::unique_ptr<Foo[]> upFoo(new Foo[128]);
whereas for a std::shared_ptr
things are uglier
// must specify deleter :(
std::shared_ptr<Foo> spFoo( new Foo[128], []( Foo *p ) { delete[] p; } );
More than that, the compiler allows me to write something like
// don't do it :(
std::shared_ptr<Foo> spFoo( new Foo[128]);
but then at deletion calls delete spFoo;
instead of the correct delete[] spFoo;
.