Avoiding const?

Jonathan M Davis jmdavisProg at gmx.com
Tue Feb 21 17:43:44 PST 2012


On Wednesday, February 22, 2012 01:25:12 BLM wrote:
> If you have a const array, you can create a non-const copy of the array
> using the .dup property of the array. The reason that you need this is that
> dynamic-length arrays share data when you assign them between variables,
> and you can't have a non-const variable using something else's const data
> without running into some really nasty problems.
> 
> In your specific case, though, the .dup property might not convert the inner
> levels of the nested array. If it doesn't work, you could try something
> like this:
> 
> char[][] words;
> words.length = set.keys.length;
> foreach(size_t i, const char[] text; set.keys) {
> words[i] = text.dup;
> }
> 
> If you don't really need to modify the individual characters in the array,
> you might just want to stick with const; it will be more efficient. You
> might also want to define the set as bool[string] because associative
> arrays prefer const/immutable keys for some reason.

The inner characters are going to need to be immutable anyway.

bool[char[]] set;

doesn't work, because the key isn't immutable. When he tries to use it the 
compiler will scream at him (though ideally, it wouldn't even let him declare 
it - there's a bug report on that). So, his AA is going to need to be

bool[string] set;

Then there's not need to dup the inner array unless he really insists on 
having the chars be mutable. But it would be far more normal to leave them as 
immutable - i.e. as string. So, all he should need is

auto words = set.keys.dup;

and he'll get a string[].

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list