Stop function parameters from being copied.

Lars T. Kyllingstad public at kyllingen.NOSPAMnet
Thu Oct 7 09:00:19 PDT 2010


On Thu, 07 Oct 2010 14:43:25 +0000, Benjamin Thaut wrote:

> If I want to tell the compiler that a certain function argument should
> not be copied (say a large struct, or a array) which is the right way to
> do?
> 
> arrays:
> 1. function foo(in float[] bar) { ... } 2. function foo(ref
> const(float[]) bar) { ... } 3. something else


Just to complement what Steven and Simen have already said, I always find 
it useful to think of arrays as structs.  For instance, int[] is 
equivalent to

    struct IntArray
    {
        size_t length;
        int* ptr;
    }

where ptr contains the memory location of the array data.  (In fact, the 
above is not only a conceptual equivalence.  The struct above is exactly, 
bit for bit, how a D array is implemented.)

Fixed-size arrays (aka. static arrays), on the other hand, are value 
types, so there the equivalence goes something like

    // int[3]
    struct IntArray3
    {
        int element0;
        int element1;
        int element2;
    }

Therefore, if you want to pass large fixed-size arrays to a function, 
you'd better use 'ref' like you would with large structs.

-Lars


More information about the Digitalmars-d-learn mailing list