开发者

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

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 i开发者_StackOverflow社区nside a parameter list.)


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.


Searching on the digital mars newsgroup, I found two semi-related post about scope in that context: here and here.

From reading those two post, function parameter scope doesn't seem to do anything useful and it's there for backwards compatibility. It even sounds like later versions after D2 might have that qualifier removed altogether.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜