How to use D without the GC ?
drug007
drug2004 at bk.ru
Wed Jun 12 21:59:54 UTC 2024
On 12.06.2024 23:56, bachmeier wrote:
> On Wednesday, 12 June 2024 at 20:37:36 UTC, drug007 wrote:
>> On 12.06.2024 21:57, bachmeier wrote:
>>> On Wednesday, 12 June 2024 at 18:36:26 UTC, Vinod K Chandran wrote:
>>>> On Wednesday, 12 June 2024 at 15:33:39 UTC, bachmeier wrote:
>>>>> A SafeRefCounted example with main marked @nogc:
>>>>>
>>>>> ```
>>>>> import std;
>>>>> import core.stdc.stdlib;
>>>>>
>>>>> struct Foo {
>>>>> double[] data;
>>>>> double * ptr;
>>>>> alias data this;
>>>>>
>>>>> @nogc this(int n) {
>>>>> ptr = cast(double*) malloc(n*double.sizeof);
>>>>> data = ptr[0..n];
>>>>> printf("Data has been allocated\n");
>>>>> }
>>>>> }
>>>>>
>>>>> ```
>>>>>
>>>> Why not just use `ptr` ? Why did you `data` with `ptr` ?
>>>
>>> Try `foo[10] = 1.5` and `foo.ptr[10] = 1.5`. The first correctly
>>> throws an out of bounds error. The second gives `Segmentation fault
>>> (core dumped)`.
>>
>> I think you can use data only because data contains data.ptr
>
> Yes, but you get all the benefits of `double[]` for free if you do it
> that way, including the more concise foo[10] syntax.
I meant you do not need to add `ptr` field at all
```D
import std;
import core.stdc.stdlib;
struct Foo {
@nogc:
double[] data;
alias data this;
this(int n)
{
auto ptr = cast(double*) malloc(n*double.sizeof);
data = ptr[0..n];
}
}
@nogc void main() {
auto foo = SafeRefCounted!Foo(3);
foo[0..3] = 1.5;
printf("%f %f %f\n", foo[0], foo[1], foo[2]);
foo.ptr[10] = 1.5; // no need for separate ptr field
}
```
More information about the Digitalmars-d-learn
mailing list