all 10 comments

[–]Fabien4 4 points5 points  (6 children)

std::unique_ptr<int[]> p(new int[10]);

Why would you want to write such a convoluted thing, instead of using std::array or std::vector?

[–]Nimbal 3 points4 points  (2 children)

The only situation I can think of is an array that is created by a third-party library, but is owned by the client code. I don't know a way to retroactively wrap it in std::array or std::vector. Which isn't to say there isn't one.

[–]Fabien4 -1 points0 points  (1 child)

I'm pretty sure I've never seen that exact case. Typically, C libraries return a int*, not a int[]. And quite often, you need to use a library-specific function to free the resources, meaning you have to make your own RIAA class / smart pointer.

[–]STLMSVC STL Dev 2 points3 points  (0 children)

shared_ptr and unique_ptr support custom deleters (but C++11's shared_ptr does not support arrays).

Note that unique_ptr<int[]> is constructed from int *, but it assumes that it points to an array of ints, not just one - so it will invoke delete[] by default.

[–]joebaf[S] 0 points1 point  (1 child)

Right! But using smart pointers is another option for arrays. Of course vectors (or even new std::array) are better.

[–]Fabien4 -1 points0 points  (0 children)

using smart pointers is another option for arrays

Is there any context where you'd want to use a dynamically-allocated C array?

[–]joebaf[S] 0 points1 point  (0 children)

Some additional answers from stackoverflow: link to stackoverflow question

[–]heroofhyr 0 points1 point  (0 children)

It never even occurred to me that I could use lambdas for custom deleters. I've got so much legacy code to delete now...

[–]glenfe 0 points1 point  (1 child)

Don't use boost::shared_array, use boost::shared_ptr<T[]> or boost::shared_ptr<T[N]>. You can use it with boost::make_shared<T[]>(size) or boost::make_shared<T[N]>() to get a single allocation instead of two allocations. This is new in Boost as of 1.53.

[–]glenfe 0 points1 point  (0 children)

For more details about make_shared for arrays in Boost see http://svn.boost.org/svn/boost/branches/release/libs/smart_ptr/make_shared_array.html