www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - scope as storage class

reply "Namespace" <rswhite4 googlemail.com> writes:
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);
}
Sep 27 2012
parent reply "Namespace" <rswhite4 googlemail.com> writes:
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?
Sep 27 2012
parent reply "bearophile" <bearophileHUGS lycos.com> writes:
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
Sep 27 2012
parent reply "Namespace" <rswhite4 googlemail.com> writes:
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);
}
Sep 27 2012
next sibling parent "bearophile" <bearophileHUGS lycos.com> writes:
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
Sep 27 2012
prev sibling parent "Jonathan M Davis" <jmdavisProg gmx.com> writes:
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
Sep 27 2012