I need some help here.

Damian damian.pop at gmail.com
Thu Aug 31 07:29:28 PDT 2006


>> 
>> Two ways.  First way, if it makes sense you might overload the index 
>> operators for your class.  If that doesn't make logical sense, then 
>> there is the .dup property which will create a safe copy:
>> 
>> # char[][] data () {
>> #   return _data.dup;
>> # }
>> 
>> I don't remember ever using .dup with multi-dimensional arrays, though, 
>> so it may have to be something more like:
>> 
>> # char[][] data () {
>> #   char[][] copy;
>> #   copy.length = _data.length;
>> #   foreach (i, x; _data) {
>> #     copy[i] = x.dup;
>> #   }
>> #   return copy;
>> # }
>> 
>> I would say experiment with the first one first.  I imagine it should 
>> work fine, and is certainly less work than the second.
>> 
>> -- Chris Nicholson-Sauls
> 
> This is really the immutability problem again. Basically, you want to 
> either:
> - not allow modification of _data; or
> - be aware when _data is changed.
> 
> Chris's suggestion (dup'ing it) achieves the first, and providing the 
> index operator achieves the second by intercepting indexing calls.
> 
> Another suggestion, if you don't want to overload indexing for your 
> class is to create an array wrapper which notifies your class on changes:
> 
> class MyArray(T) {
> 	private T[] _data;
> 	
> 	T opIndexAssign(uint index, T value) {
> 		notifyThatDataHasChanged();
> 		return _data[index] = value;
> 	}
> 
> 	T opIndex(uint index) {
> 		return _data[index];
> 	}
> 	...
> }
> 
> This means that you can use your class's opIndex for something else. 
> Alternatively, you could use this interface to return an immutable 
> version of _data, just by not supporting opIndexAssign.
> 
> Cheers,
> 
> Reiner

Well, I thought I was missing a "const" somewhere, but it's a little more
complicated. :S
1st choice: Make a copy of 2-dim array seems to be a waste of time to this
specific problem.
2nd choice: My class is not a "data" class, it just works with some data,
so overload index ops in my class isn't clear, I think.
3rd choice:I don't want to make a class wrapper since all I need is an
array, but well, I think I can do it once and use it once and again, so
I'll take this choice! 
Anyway, I think I miss "const". Why is not part of D?

Thanks you both for your help!




More information about the Digitalmars-d-learn mailing list