www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - I don't quite get foreach ref

reply Tomek =?UTF-8?B?U293acWEc2tp?= <just ask.me> writes:
struct DumbRange {
    int front() { return 5; }             // rvalue
    void popFront() { --counter; }
    bool empty() { return counter > 0; }
    uint counter = 10;
}

void clear(ref int a) { a = 0; }

void main() {
    auto r = DumbRange();

    // Doesn't compile (and good): r.front() is not an lvalue
    clear(r.front);

    // Confusingly has no effect. Yet, compiles -- should it?
    foreach(ref a; r) a = 0;
}

I don't know what to make of it, the D page says nothing on foreach ref on
rvalues.


Tomek
Aug 08 2010
next sibling parent Tomek =?UTF-8?B?U293acWEc2tp?= <just ask.me> writes:
Tomek Sowiński napisał:

 bool empty() { return counter > 0; }
Should of course be counter == 0;
Aug 08 2010
prev sibling parent "Steven Schveighoffer" <schveiguy yahoo.com> writes:
On Sun, 08 Aug 2010 06:01:20 -0400, Tomek Sowiński <just ask.me> wrote:

 struct DumbRange {
     int front() { return 5; }             // rvalue
     void popFront() { --counter; }
     bool empty() { return counter > 0; }
     uint counter = 10;
 }

 void clear(ref int a) { a = 0; }

 void main() {
     auto r = DumbRange();

     // Doesn't compile (and good): r.front() is not an lvalue
     clear(r.front);

     // Confusingly has no effect. Yet, compiles -- should it?
     foreach(ref a; r) a = 0;
 }

 I don't know what to make of it, the D page says nothing on foreach ref  
 on rvalues.
Historically, when using opApply to implement foreach, opApply's delegate must take all ref arguments. This is a source of pain because if you don't want to ref your data, you had to make temporary copies. I don't know why ranges have propagated this silliness. You should file a bug. Also vote for mine: http://d.puremagic.com/issues/show_bug.cgi?id=2443 -Steve
Aug 09 2010