www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Why is the struct instance being copied here?

reply d coder <dlang.coder gmail.com> writes:
Greetings

Please look at the code down here. When compiled and run, I get the message
"Call to postblit" printed. I think it is because of the foreach block,
because the variable "i" is not declared as ref there. Is there a way to
make it a ref?

Regards
- Puneet

import std.stdio;

struct Foo {
  this(this) {
    writeln("Call to postblit");
  }
}

class Bar {
  Foo foo;
  this() {
    foreach(i, f; this.tupleof) {
      // do nothing
    }
  }
}

void main()
{
  Bar bar = new Bar();
}
Mar 11 2011
parent "Steven Schveighoffer" <schveiguy yahoo.com> writes:
On Fri, 11 Mar 2011 04:50:38 -0500, d coder <dlang.coder gmail.com> wrote:

 Greetings

 Please look at the code down here. When compiled and run, I get the  
 message
 "Call to postblit" printed. I think it is because of the foreach block,
 because the variable "i" is not declared as ref there. Is there a way to
 make it a ref?

 Regards
 - Puneet

 import std.stdio;

 struct Foo {
   this(this) {
     writeln("Call to postblit");
   }
 }

 class Bar {
   Foo foo;
   this() {
     foreach(i, f; this.tupleof) {
       // do nothing
     }
   }
 }

 void main()
 {
   Bar bar = new Bar();
 }
This typically works in a foreach loop: foreach(i, ref f; x) but a foreach for a tuple is a special beast, and using ref in your code yields this error: foreachtuple.d(12): Error: no storage class for value f But I agree it should be doable. This should qualify for an enhancement request: http://d.puremagic.com/issues/enter_bug.cgi?product=D -Steve
Mar 11 2011