DIP1000 scope inference
Paul Backus
snarwin at gmail.com
Tue Oct 25 02:09:02 UTC 2022
On Tuesday, 25 October 2022 at 01:35:28 UTC, Steven Schveighoffer
wrote:
> Does the inferred `scope` make it so that the compiler is
> *allowed* to allocate the `[4, 5, 6]` literal on the stack?
> Keep in mind that I never put `scope` here, this is something
> the compiler did on its own.
No, it does not. This capability was added only for array
literals, and only for variable initialization:
DMD PR: https://github.com/dlang/dmd/pull/14562
Spec PR (pending): https://github.com/dlang/dlang.org/pull/3442
However, this thread raises an important point: changing the way
existing language constructs allocate memory in the presence of
`scope` may cause `@trusted` code which relied on the original
behavior to become unsound.
For example, the `@trusted` function below is memory safe when
using the current compiler release, but will become unsafe when
compiled with DMD 2.101:
```d
@trusted int[] example()
{
scope example = [1, 2, 3];
return example;
}
```
The worst part is that the potential memory corruption is
introduced silently. Users who upgrade to DMD 2.101 will have no
idea that the ground has shifted beneath their feet until their
code invokes UB at runtime.
More information about the Digitalmars-d
mailing list