Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Meaning of "scope" in D (for a parameter)

Tags:

d

What does scope in

void foo(scope void* p) { }

mean?

(I'm not talking about scope(exit) or scope int x = 5;, but about scope as used inside a parameter list.)

like image 747
user541686 Avatar asked Jan 17 '11 08:01

user541686


1 Answers

There are 3 uses for scope in D.

  1. scope statements. This is when you use scope(success), scope(failure), or scope(exit). The statements in the block that follows are run when exiting the scope that the scope statement is in if no exception is thrown, if an exception is thrown, or regardless of whether an exception is thrown for success, failure, and exit respectively. This use of scope is staying in the language.

  2. scope on a local variable. This puts the variable on the stack - even if it's a class. The object is destroyed when it leaves scope. This use of scope is unsafe and will eventually be removed from the language (though std.typecons.scoped replaces it for those who want to live life dangerously).

  3. scope on a function parameter (which is the use case that you're asking about). When placed on a parameter that is a delegate, it means that references to that parameter cannot be escaped (i.e. assigned to a global variable). And when the compiler sees this on delegates, it will avoid allocating a closure when taking the address of a local function. This is essential in opApply loops (reference post on newsgroup). Currently, scope has no effect on any function parameters other than delegates and is ignored for all other types, though it may or may not at some point in the future be expanded to affect types like pointers to prevent them from escaping the function.

When used on a function parameter, the in keyword is an alias for const scope, which is frequently how scope on function parameters gets inadvertently used.

like image 136
Jonathan M Davis Avatar answered Sep 24 '22 14:09

Jonathan M Davis