4 hours ago Pointer vs Ref | ||||
---|---|---|---|---|
| ||||
Hello community, Is it possible to accomplish the following using ref instead of pointers? If so, please share an example. import std.stdio; // Represents our large, external data source (like TimeSeries) struct DataSource { int[3] data; } // 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); } } } void main() { writeln("--- Running Pointer Member Example ---"); // 1. Create our data. It lives here in main. auto myData = DataSource([10, 20, 30]); // 2. Create our engine. It starts empty. auto myEngine = Engine(); writeln("Engine created. Has it been configured yet?"); myEngine.run(); // Will fail because the pointer is null // 3. Configure the engine. We give it the ADDRESS of our data. // The engine stores this address in its pointer member. writeln("\nConfiguring engine..."); myEngine.dataSource = &myData; // 4. Later, we run the engine. It can now work because it // remembered the address of myData. writeln("\nRunning configured engine..."); myEngine.run(); } Thanks, -- confuzzled |
Copyright © 1999-2021 by the D Language Foundation