Pointer vs Ref
confuzzled
con at fuzzled.com
Fri Jul 4 16:00:14 UTC 2025
On 6/15/25 9:06 AM, Steven Schveighoffer wrote:
> 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.
>
>
> 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
This is perfect. Thanks Steve. I had all but given up on this.
More information about the Digitalmars-d-learn
mailing list