Wanting an immutable associative array in a class

Lars T. Kyllingstad public at kyllingen.NOSPAMnet
Fri Jul 30 02:25:55 PDT 2010


On Thu, 29 Jul 2010 22:55:35 -0400, bearophile wrote:

> RedZone:
>> But it would be nice if I could have the array reference itself be
>> immutable and not just the array's contents.  Is there any way I could
>> do this?
> 
> Let's say your code is as your second example:
> 
> class Foo {
>     private:
>         immutable int[string] bar;
> 
>     public:
>         this() {
>             bar = ["AB":1, "CD":2, "EF":3];
>         }
> }
> 
> void main() {
>     auto f = new Foo;
> }
> 
> 
> How can you change the array reference outside the class constructor?


But that was not his second example. :)  His second example used the type

  immutable(int)[char[]]

while you used the "correct" one,

  immutable(int[char[]])

RedZone:  Even though the overall type is immutable, you can still set it 
in a constructor, like bearophile showed.

May I also suggest a small improvement?  Doing it like this means that 
the array will be constructed anew every time you create an instance of 
the class.  If it's meant to be immutable, and you know all the elements 
of the array at compile time, that's just wasteful.  In that case, it's 
probably better to make it a static member variable, and set its value in 
a static constructor.  That way it will only get constructed once, at 
program startup.

  class Foo
  {
  private:
      static immutable int[string] bar;

      static this()  // Only run when program loads
      {
          bar = ["AB": 1, "CD": 2, "EF": 3];
      }

  public:
      ...
  }

-Lars


More information about the Digitalmars-d-learn mailing list