Pointer vs Ref

Steven Schveighoffer schveiguy at gmail.com
Sun Jun 15 00:06:36 UTC 2025


On Monday, 9 June 2025 at 07:24:41 UTC, confuzzled wrote:
> Hello community,
>
> Is it possible to accomplish the following using ref instead of 
> pointers? If so, please share an example.

> ```d
> // Represents our Backtester engine
> struct Engine
> {
>     // It STORES a pointer to its data source. This is its 
> "memory".
>     const(DataSource)* dataSource;
>
>     // The run method USES the stored pointer.
>     void run()
>     {
>         writeln("Engine running...");
>         if (dataSource is null)
>         {
>             writeln("  Error: Data source not configured!");
>             return;
>         }
>
>         // We access the data through the remembered pointer.
>         foreach (i, val; dataSource.data)
>         {
>             writef("  Processing data point %d: %d\n", i, val);
>         }
>     }
> }

A ref cannot be a member of a type. But ref can be returned by a 
function.

So what you want is a *property* function:

```d
struct Engine
{
     private const(DataSource)* _dataSourceStorage;

     this(ref const(DataSource) dataSource)
     {
         this._dataSourceStorage = &dataSource;
     }

     @property ref dataSource() => *_dataSourceStorage;

     ... // rest the same
}

...

void main()
{
     auto myData = DataSource([10, 20, 30]);
     auto myEngine = Engine(myData); // initialize via ref
     ...
}
```

-Steve


More information about the Digitalmars-d-learn mailing list