D: Declaring empty pointer variables that return address inside function calls?

Julian Fondren julian.fondren at gmail.com
Thu Nov 23 20:40:14 UTC 2023


On Thursday, 23 November 2023 at 20:13:59 UTC, BoQsc wrote:
> Nothing wrong. It would be just a more concise compact way to 
> do the same.
>
> Also I mostly wanted to know if something like that is already 
> possible in D language.
>
> It's not a huge loss if it is not possible.

This is possible in Go: you dereference a literal constructor and 
it's either built on the stack or the heap depending on escape 
analysis. Example:

```go
package main

import "fmt"

type T struct {
	data [5]byte
}

func usebuffer(a *T) *T {
	a.data[0] = 1
	a.data[4] = 10
	return a
}

func f() *T {
	return usebuffer(&T{}) // <--
}

func main() {
	fmt.Println(f())
}
```

which is very close to this D that is explicitly allocating on 
the heap:

```d
class T {
	byte[5] data;
}

T usebuffer(T a) {
	a.data[0] = 1;
	a.data[4] = 10;
	return a;
}

T f() {
	return usebuffer(new T()); // <--
}

void main() {
	import std.stdio : writeln;
	writeln(f().data);
}
```

Which if you want stack allocation, is very similar to:

```d
class T {
	byte[5] data;
}

T usebuffer(T a) {
	a.data[0] = 1;
	a.data[4] = 10;
	return a;
}

void main() {
	import std.stdio : writeln;
	import std.typecons : scoped;

	writeln(usebuffer(scoped!T).data);
}
```

but, I don't actually know if this is safe.


More information about the Digitalmars-d-learn mailing list