On Sunday, 24 August 2025 at 15:03:12 UTC, Brother Bill wrote:
On page 549 of Programming in D, it appears that D supports
'escaping' local variables to the heap, when returning their
address.
This is similar to Go.
Is this what is actually going on?
Is this 'safe' to do?
```
&result: AC067AF730
&result: AC067AF730
ptrSum : AC067AF7B0 (2 + 3)
sum : (4 * 5)
```
source/app.d
```
import std.stdio;
void main() {
string * ptrSum = &parenthesized("2 + 3");
string sum = parenthesized("4 * 5");
writefln("ptrSum : %s %s", ptrSum, *ptrSum);
writefln("sum : %s", sum);
}
auto ref string parenthesized(string phrase) {
string result = '(' ~ phrase ~ ')';
writeln("&result: ", &result);
return result; // ← compilation ERROR
}
```
I don't know what's happening here, but it seems like a bug. This
should not compile (it does for me, despite the comment above).
If you change `auto ref` to just `ref`, it fails, and if you
change it to just returning `string` it fails.
If you change it to returning `auto ref` without `string`, it
also fails.
It appears that the address taken is one of a local stack
temporary.
-Steve