STL like Vector,Pair, Map

Regan Heath regan at netmail.co.nz
Wed Nov 14 01:26:24 PST 2007


Tim Keating wrote:
> Bill Baxter Wrote:
> 
>>> Why?
>> STL containers act like value types.
>> 
>> std::vector<int> a,b; ...// put some stuff in vector a b = a;  //
>> now b has a copy of every element of a a[4] = 9;  //b[4] unchanged
>> 
>> 
>> In D currently to get that behavior have to do .dup: int[] a,b; b =
>> a.dup;
> 
> But . . . the reason the STL uses value types is to minimize the
> complexity inherent in determining who owns objects passed by
> reference. Doesn't that problem just _go away_ in a garbage-collected
> language?

To some extent yes.  To the extent that you no longer need to figure out 
if you can free the memory associated with it.  However not to the 
extent that if you have say, a string/char[] and want to know if you 
need to dup it in order to modify it.

In the latter case if following D guidelines you would 'copy on write' 
AKA make a dup and write to the dup.  However, in the case where you had 
the only reference to the object this is less efficient.

Reference counting could be used but I suspect the overhead of managing 
them probably cancels out any gains.

I just wondered if the garbage collector could calculate reference 
counts on the fly... however I guess these could only be relied on 
immediately after they were generated and would therefore be of limited use.

> Could you not build an interface-compatible set of STL containers
> that use reference semantics instead? Admittedly, that's a big caveat
> for porting, but I wonder how much code you would actually have to
> change . . .

If you also used copy on write when modifying objects in the collection 
then you could, and you'd even gain some performance as copies are only 
made when changes are made to the objects.

Regan



More information about the Digitalmars-d mailing list