www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - ref & address

reply "Chris" <wendlec tcd.ie> writes:
The following:

     this(ref InputRange r) {
       writeln(&r);
       this.r = r;
       writeln(&this.r);
     }


7FFF2BD74D50  // r
7FFF2BD745F0  // this.r

Why? And how can I change this?
Apr 16 2014
parent reply "Adam D. Ruppe" <destructionator gmail.com> writes:
What's the definition of InputRange? Is it the interface from 
std.range?

If so, don't pass it as ref. interfaces are references to the 
object by default.

In general, you only need ref when you want to assign a new 
object to the variable and want that change to be seen outside 
the function too.
Apr 16 2014
parent reply "Chris" <wendlec tcd.ie> writes:
On Wednesday, 16 April 2014 at 16:21:42 UTC, Adam D. Ruppe wrote:
 What's the definition of InputRange? Is it the interface from 
 std.range?

 If so, don't pass it as ref. interfaces are references to the 
 object by default.

 In general, you only need ref when you want to assign a new 
 object to the variable and want that change to be seen outside 
 the function too.
InputRange is an array of structs. this is also a struct, a range that manipulates elements in the InputRange (i.e. it calculates values and stores them in fields of each struct that is in the array).
Apr 16 2014
parent reply "Adam D. Ruppe" <destructionator gmail.com> writes:
OK, you could also store a pointer to the InputRange as your 
member.

With structs, assignment is making a private copy, so if you want 
to update the original in a stored thing you'll need the pointer. 
ref doesn't work with anything other than function arguments in D.
Apr 16 2014
parent "Chris" <wendlec tcd.ie> writes:
On Wednesday, 16 April 2014 at 17:20:52 UTC, Adam D. Ruppe wrote:
 OK, you could also store a pointer to the InputRange as your 
 member.

 With structs, assignment is making a private copy, so if you 
 want to update the original in a stored thing you'll need the 
 pointer. ref doesn't work with anything other than function 
 arguments in D.
Yeah, I've started to realize that. The thing is, I have an almost identical range in a another module and it does exactly what I want it to do, i.e. the InputRange is passed by reference with ref and all changes become visible as soon as they happen. Anyway, I'll try a pointer solution and see what happens. For efficiency's sake I don't want to copy anything.
Apr 16 2014