Inserting to associative array do not return a lvalue.

Bill Baxter dnewsgroup at billbaxter.com
Tue Oct 16 10:21:33 PDT 2007


BCS wrote:
> Reply to Yang,
> 
>> Sorry. I thought I have a mistake. Holding a pointer to the value of
>> an associative array is very dangerious.Yang Bo ??:
>>
> 
> 
> this works
> 
> int[int] a;
> a[1] = 2;
> int* r = 1 in a;
> (*r)++;
> 
> assert(2 == a[1]);

Yeh, I don't think there's anything wrong with modifying the value.

But your version does two lookups also.  Yang makes a good point.  The 
AA *has* a pointer to the node it just inserted, it just doesn't return 
it (or a pointer to the value).  Compare with STL map where the insert 
function returns an iterator to the inserted node.

Really the problem is that D doesn't have a reference type constructor 
(just a parameter storage class).  In a D-with-references world, a[1] = 
2 would return a reference to the value instead of a copy.

Another possible solution would be to require all pointer arithmetic to 
use an explicit &, similar to how function pointers work in D.  Then a 
plain Foo* would be able act like basically like a reference, and a[1] = 
2 could happily return a pointer.  But that's probably too big a change 
to happen now.  And probably too confusing for C/C++ folks, anyway.
    Foo *foo;  foo = 3;  // huh?

--bb



More information about the Digitalmars-d mailing list