struct / cast / ? design problem

ketmar via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Mar 16 13:46:07 PDT 2015


On Mon, 16 Mar 2015 12:49:40 -0700, Charles Hixson via Digitalmars-d-learn
wrote:

yep, you're doing it wrong, as Marc already wrote. ;-)

it's not very obvious, but this line makes a copy:

  auto val = tst.value;

there are no `ref` type in D. `ref` is modifier for function arguments, 
but not part of the type, and you can't declare `ref int`, for example. 
so that line transforms to this:

  ubyte[400] val = tst.value;

which, obviously, does copying. yet this will work as expected:

  import iv.writer;

  struct tstHead {
    ubyte[400] data;

    ubyte[] value () { return data; }
    void write (int i) { writeln(data[i]); }
  }


  void test (ref ubyte[400] a) {
    a[2] = 42;
  }


  void main () {
    tstHead tst;
    auto val = tst.value;
    val[23] = 23;
    writeln(val[23]);
    tst.write(23);
    tst.write(0);
    test(val[0..400]);
    tst.write(2);
  }

-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 181 bytes
Desc: not available
URL: <http://lists.puremagic.com/pipermail/digitalmars-d-learn/attachments/20150316/a3af696c/attachment.sig>


More information about the Digitalmars-d-learn mailing list