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.)
There are 3 uses for scope
in D.
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.
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With