On Wed, 06 Oct 2010 06:16:45 -0400, Lars T. Kyllingstad <[email protected]> wrote:

I have a program that uses an immutable array, the contents of which are
known at compile time.  Thus, ideally, I want it to be placed in
the .rodata segment of the program.

Firstly, I seem to remember reading that using an array literal in D will
always result in a heap allocation.  Is this correct?

Yes. There is no way to create an immutable array besides a string in read only memory. Even enums will result in array literals being created on the heap whenever you refer to them (there's a bug related to this somewhere).

Secondly, if the above is not true, how can I verify that the array in
the following piece of code isn't allocated and/or copied anew every time
the program runs, or even worse, every time foo() is called?

  void foo()
  {
      static immutable int[3] = [1, 2, 3];
  }

Actually, static probably will prevent it from being created every time foo is called. I don't think there's a way to prevent it from being created every time the program is run.

I know, RTFAsm, but some help with that would be appreciated. ;)

Thirdly, intuition tells me that when the array is immutable, the
'static' shouldn't have an effect.  But experiments (i.e. printing the
adress of the array) indicate that it does.  Is there some reason for
this, or is it just a shortcoming of the compiler?

Of course. If you realize that the expression [1,2,3] is not immutable, then it makes sense.

Another example to help you think about it:

void foo(int x)
{
   immutable int[3] = [1,2,x];
}

This must be run on every call of foo, because x can vary.

BTW, I'm all for making array literals immutable. You can always make runtime-allocated arrays via a library function.

-Steve

Reply via email to