digitalmars.D.learn - Does scope not work on parameters?
- Russ (24/24) Feb 22 2020 Hi, I've been playing around with having classes allocated on the
- Steven Schveighoffer (10/11) Feb 22 2020 scope escapes are only disallowed in @safe code.
- Russ (4/16) Feb 22 2020 Perfect, thank you! I agree that this sort of thing should be on
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); }
Feb 22 2020
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
Feb 22 2020
On Sunday, 23 February 2020 at 03:26:17 UTC, Steven Schveighoffer wrote:On 2/22/20 10:01 PM, Russ wrote: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.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
Feb 22 2020