Boost logo

Boost :

From: Howard Hinnant (hinnant_at_[hidden])
Date: 2003-02-03 15:53:49


On Monday, February 3, 2003, at 02:44 PM, Andrei Alexandrescu wrote:

> "Howard Hinnant" <hinnant_at_[hidden]> wrote in message
> news:D82ECED1-3784-11D7-AB9E-003065D18932_at_twcny.rr.com...
>> On Sunday, February 2, 2003, at 11:40 PM, Andrei Alexandrescu wrote:
>>
>>> By and large, I believe "smart pointers to arrays" are an oxymoron
>>> and
>>> should not be supported.
>>
>> Why?
>
> The reasons are explained in MC++D. Here's my take:

Seems I've been going back to reread sections of my trusty MDC++D quite
often lately. :-)

> 1. Arrays of polymorphic objects don't work.

Right. But to me that just means you don't want to have the member
template converting constructors/assignment in your array version of
the smart pointer (as shown in boost::shared_ptr/shared_array, and the
move_ptr example at
http://home.twcny.rr.com/hinnant/Utilities/move_ptr).

> 2. If I wanna arrays of monomorphic objects I can use std::vector.

True.

> 3. If I wanna arrays of monomorphic objects and std::vector's
> performance
> is unsatisfactory to me,

Naw, couldn't happen! ;-)

> I can use the typed buffers
> (http://www.moderncppdesign.com/publications/cuj-08-2001.html,
> http://www.moderncppdesign.com/publications/cuj-10-2001.html,
> http://www.moderncppdesign.com/publications/cuj-12-2001.html) that are
> present in the up-and-coming YASLI.

Up-and-coming? I was just getting used to "legendary"! :-)

> 4. So there's no reason I'd ever wanna have smart pointers to arrays.

I agree that vector (or vector-like substitutes) are preferred over
smart_ptr<T[]> in most circumstances. But there are times when
ownership of the array needs to be transferred or shared. In those
instances, vector is not a good fit. smart_ptr<vector<T> > is a
possibility, but this is typically inferior both in performance, and in
client level syntax (e.g. (*p)[i] instead of p[i]).

Example 1: I currently have a requirement in one of my classes that it:

1. Be constructible from a null terminated char array of arbitrary
length.
2. Have a member function that returns the "string" which the object
was constructed with.
3. Have a no-throw copy constructor.

These requirements can be neatly met by having the class hold a shared
pointer (reference counted, cyclic, whatever) to an array of char.

Example 2: A routine whose function is to create and fill a
dynamically sized array and then transfer ownership of that array back
to the client. A strstream-like object might want to do this. It
could create and fill the buffer as needed, and then transfer ownership
of that buffer to the client.

-Howard


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk