2

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;.

vsoftco
  • 55,410
  • 12
  • 139
  • 252
  • Thanks for the link, didn't find the question before on so. The answer is kind of funny though :) – vsoftco Nov 26 '14 at 05:50

0 Answers0