How is this code invalid?

H. S. Teoh hsteoh at qfbox.info
Sat Dec 17 16:40:25 UTC 2022


On Sat, Dec 17, 2022 at 02:36:10AM +0000, thebluepandabear via Digitalmars-d-learn wrote:
[...]
> Thanks, I've tried to mark it with `@safe` and it did give me a
> warning.
> 
> I was also wondering, why is this code valid?
> 
> ```D
> int[] numbersForLaterUse;
> 
> @safe void foo(int[] numbers) {
> 	numbersForLaterUse = numbers;
> }
> ```

This code is safe provided the arguments are not allocated on the stack,
which is usually the case because you can no longer call it with:

	foo(1, 2, 3, 4);

but you have to write:

	foo([ 1, 2, 3, 4 ]);

The [] here will allocate a new array on the heap, so the array elements
will not go out of scope when the caller returns. (They will be
collected by the GC after all references to them have gone out of scope.
This is one of the advantages of using a GC: it saves you from having to
worry about complicated lifetimes in such cases.)

You may still run into trouble, though, if you do this:

	int[3] data = [ 1, 2, 3 ]; // N.B.: stack-allocated
	foo(data[]);	// uh oh

To guard against this, use @safe and -dip1000, which will cause the
compiler to detect this dangerous usage and generate an error.


T

-- 
Answer: Because it breaks the logical sequence of discussion. / Question: Why is top posting bad?


More information about the Digitalmars-d-learn mailing list