Thread overview
scope as storage class
Sep 27, 2012
Namespace
Sep 27, 2012
Namespace
Sep 27, 2012
bearophile
Sep 27, 2012
Namespace
Sep 27, 2012
bearophile
Sep 27, 2012
Jonathan M Davis
September 27, 2012
What is the correct use of scope as storage class?

int counter;

void foo(scope int a) {
    counter = a;
}

void main() {
   int num = 42;
foo(num);
}
September 27, 2012
My handy has send to soon....

This code:

int counter;

void foo(scope int a) {
    counter = a;
}

void main() {
    int num = 42;
    foo(num);
}

works fine but I think it should not. So can you explain me the use of scope as a storage class?
September 27, 2012
Namespace:

> int counter;
>
> void foo(scope int a) {
>     counter = a;
> }
>
> void main() {
>     int num = 42;
>     foo(num);
> }
>
> works fine but I think it should not. So can you explain me the use of scope as a storage class?

Generally such enforcement is not (well) implemented in the dmd front-end still. And I think it's mostly meant for reference types (class references and raw pointers), so even when it's implemented I think it will not give an error in your case.

Bye,
bearophile
September 27, 2012
So you mean this code should give an error?

import std.stdio;

class A { }

A ga;

void foo(scope A a) {
	ga = a;
}

void main() {
	A a = new A();
	
	foo(a);
}
September 27, 2012
Namespace:

> So you mean this code should give an error?
>
> import std.stdio;
>
> class A { }
>
> A ga;
>
> void foo(scope A a) {
> 	ga = a;
> }
>
> void main() {
> 	A a = new A();
> 	
> 	foo(a);
> }

I think so.

Bye,
bearophile
September 27, 2012
On Thursday, September 27, 2012 14:01:39 Namespace wrote:
> So you mean this code should give an error?
> 
> import std.stdio;
> 
> class A { }
> 
> A ga;
> 
> void foo(scope A a) {
> ga = a;
> }
> 
> void main() {
> A a = new A();
> 
> foo(a);
> }

Yes. You escaped a reference, which scope is supposed to prevent, but it rarely actually complains even though it's supposed to. Odds are that a lot of uses of scope (and in, since in is const scope) are going to break once scope has been fixed.

- Jonathan M Davis