Why is this allowed
tsbockman
thomas.bockman at gmail.com
Wed Jul 1 20:10:53 UTC 2020
On Wednesday, 1 July 2020 at 20:05:51 UTC, tsbockman wrote:
> If you want the compiler to stop you from accidentally keeping
> references to stack variables past the end of their scope, you
> need to annotate your functions @safe and compile with
> -preview=dip1000: https://run.dlang.io/is/3VdDaN
>
> Furthermore, the problem your example shows has nothing to do
> with implicit static to dynamic array conversion, as without
> @safe the same error can easily be committed with non-array
> types: https://run.dlang.io/is/nBjibd
Hmm. Those run.dlang.io short links seem to allow editing of the
code, so I'd better paste it here for permanence:
// Compile with -preview=dip1000
struct Database {
int[] data;
void set(int[] _data) @safe {
data = _data;
}
}
void myFunc(ref Database db) @safe {
int[3] x;
db.set(x); // This is a compile-time error, as it should be.
}
Database theDB;
void main() {
myFunc(theDB);
}
// This version shows that the problem is not using @safe and
dip1000,
// not anything to do with arrays:
struct Database {
int* data;
void set(ref int _data) {
data = &_data;
}
}
void myFunc(ref Database db) {
int x;
db.set(x); // oops
}
Database theDB;
void main() {
myFunc(theDB);
}
More information about the Digitalmars-d-learn
mailing list