问题
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.
scopestatements. This is when you usescope(success),scope(failure), orscope(exit). The statements in the block that follows are run when exiting the scope that thescopestatement 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 ofscopeis staying in the language.scopeon 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 ofscopeis unsafe and will eventually be removed from the language (though std.typecons.scoped replaces it for those who want to live life dangerously).scopeon 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 inopApplyloops (reference post on newsgroup). Currently,scopehas 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