Meaning of “scope” in D (for a parameter)

删除回忆录丶 提交于 2020-12-29 09:14:07

问题


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.)


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/4711309/meaning-of-scope-in-d-for-a-parameter

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!