Deprecation: returning this escapes a reference to parameter this

Viewed 210

Ran into this while updating DMD to 2.094.1 in our codebase. What is it about and how to fix it?

Deprecation: returning this escapes a reference to parameter this
       perhaps annotate the parameter with return

The warning was emitted for the return this; line:

public ref EventBuilder typeOne()
{
    this.type = 1;
    return this;
}
1 Answers

This deprecation warning is related to DIP25. Add a return right here:

public ref EventBuilder typeOne() return
{
    this.type = 1;
    return this;
}

Quoting the Changelog for DMD 2.092.0:

DIP25 has been available since v2.067.0, first as its own switch, and more recently under the -preview=dip25 switch. The feature is now fully functional and has been built on, for example by DIP1000.

Starting from this release, code that would trigger errors when -preview=dip25 is passed to the compiler will also trigger a deprecation message without -preview=dip25. The behavior of the switch is unchanged (errors will still be issued).

DIP25 aims to make it impossible for @safe code to refer to destructed object. In practice, functions and methods returning a ref to their parameter might be required to qualify the method or the parameter as return, as hinted by the compiler.

struct Foo
{
    int x;
    // returning `this.x` escapes a reference to parameter `this`,
    // perhaps annotate with `return`
    ref int method() /* return */ { return this.x; }
}
// returning `v` escapes a reference to parameter `v`,
// perhaps annotate with `return`
ref int identity(/* return */ ref int v) { return v; }

In both cases, uncommenting the return annotation will appease the compiler.

Related