Thread overview | |||||
---|---|---|---|---|---|
|
February 23, 2020 Does scope not work on parameters? | ||||
---|---|---|---|---|
| ||||
Hi, I've been playing around with having classes allocated on the stack. I am using the scope keyword for local variables. I assumed that the scope modifier for function parameters was designed to prevent these from escaping, but the code below doesn't show any errors. Is there some newer feature I should be using? Thanks. import std.stdio; class Foo { } class Bar { Foo foo; } void doSomething(scope Foo z, Bar b) { b.foo = z; } void main() { Bar b = new Bar; scope foo = new Foo; doSomething(foo, b); } |
February 22, 2020 Re: Does scope not work on parameters? | ||||
---|---|---|---|---|
| ||||
Posted in reply to Russ | On 2/22/20 10:01 PM, Russ wrote:
> Is there some newer feature I should be using?
scope escapes are only disallowed in @safe code.
Adding @safe: to the top of this file makes it not compile with a complaint:
Error: scope variable z assigned to non-scope b.foo
Which I think is what you expected.
As to why it happens without @safe, you may be managing your global variable carefully and ensuring it's unset by the time foo goes away. The compiler can't know.
Another reason to enable safe-by-default...
-Steve
|
February 23, 2020 Re: Does scope not work on parameters? | ||||
---|---|---|---|---|
| ||||
Posted in reply to Steven Schveighoffer | On Sunday, 23 February 2020 at 03:26:17 UTC, Steven Schveighoffer wrote:
> On 2/22/20 10:01 PM, Russ wrote:
>> Is there some newer feature I should be using?
>
> scope escapes are only disallowed in @safe code.
>
> Adding @safe: to the top of this file makes it not compile with a complaint:
>
> Error: scope variable z assigned to non-scope b.foo
>
> Which I think is what you expected.
>
> As to why it happens without @safe, you may be managing your global variable carefully and ensuring it's unset by the time foo goes away. The compiler can't know.
>
> Another reason to enable safe-by-default...
>
> -Steve
Perfect, thank you! I agree that this sort of thing should be on by default. Better to opt-out than opt-in for memory safety.
|
Copyright © 1999-2021 by the D Language Foundation