www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - scope front vs [0]

reply vitamin <vit vit.vit> writes:
Hello,
Why does expression 'foo = bars[][0].foo' work but 'foo = 
bars[].front.foo' doesn't?

example:


class Foo{}

struct Bar{
	Foo foo;
}

void main() safe{
	import std;

     Foo foo;
     scope Bar[] bars = [Bar.init];

     foo = bars[][0].foo;		//OK, WHY?
     foo = bars[].front.foo;		//Error: scope variable bars 
assigned to foo with longer lifetime
}
Nov 11 2020
parent vitamin <vit vit.vit> writes:
Or similar problem:

class Foo{}

struct Slice{
     Foo[] data;

     this(return scope Foo[] data) safe {
         this.data = data;
     }
     Slice opSlice() safe return scope{
         return Slice(data);
     }
     Foo opIndex(size_t i) safe return scope{
         return data[i];
     }
}

void main() safe{
     Foo foo;
     scope Slice slice = Slice([new Foo]);

     foo = slice[][0];		//OK, Why?
     foo = slice[].opIndex(0);	//Error: scope variable slice 
assigned to foo with longer lifetime
}
Nov 11 2020