return scope ref outlives the scope of the argument
Eugene Wissner
belka at caraus.de
Tue Jun 25 11:27:31 UTC 2019
On Tuesday, 25 June 2019 at 11:16:47 UTC, Jonathan M Davis wrote:
> On Tuesday, June 25, 2019 1:32:58 AM MDT Eugene Wissner via
> Digitalmars-d- learn wrote:
>> struct Container
>> {
>> }
>>
>> static struct Inserter
>> {
>> private Container* container;
>>
>> private this(return scope ref Container container)
>> @trusted
>> {
>> this.container = &container;
>> }
>>
>> }
>>
>> auto func()()
>> {
>> Container container;
>> return Inserter(container);
>> }
>>
>> void main()
>> {
>> static assert(!is(typeof(func!())));
>> }
>>
>> The code above compiles with dmd 2.085, but not 2.086 (with
>> -preview=dip1000). What am I doing wrong?
>
> You're storing a pointer to a scope variable. That's violating
> the entire point of scope. If something is scope, you can't
> store any kind of reference to it. And since container is a
> local variable in func, and Inserter tries to return from func
> with a pointer to container, you definitely have an @safety
> problem, because that pointer would be invalid once func
> returned.
>
> - Jonathan M Davis
So you're saying that func() shouldn't compile? And it is exactly
what the assertion in the main function does: it asserts that the
function cannot be instantiated. And it was true for 2.085 but it
can be instantiated with 2.086.
More information about the Digitalmars-d-learn
mailing list