www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Does scope not work on parameters?

reply Russ <russpowers gmail.com> writes:
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
parent reply Steven Schveighoffer <schveiguy gmail.com> writes:
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
parent Russ <russpowers gmail.com> writes:
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.
Feb 22 2020