Re: How to implement this?

2022-04-08 Thread Elvis Zhou via Digitalmars-d-learn

On Friday, 8 April 2022 at 09:08:07 UTC, Stanislav Blinov wrote:

On Friday, 8 April 2022 at 05:53:03 UTC, Elvis Zhou wrote:


assumeNoEscapeOrWhatever!DynamicArray structs;
structs ~= cast(A*)

is it possible?


That's what `@trusted` is for. And that's also why it should be 
used with care, and on the smallest code possible.


```d
struct A {}
struct B { A a; }
struct C { A a; }

void main()
{
A*[] structs;

B b;
C c;

() @trusted {
structs ~= cast(A*)
structs ~= cast(A*)
} ();
}
```


Thank you, this is exactly what I'm looking for!

But why this doesn't work?
void func() @trusted
{
A*[] structs;
B b;
structs ~= cast(A*) // still error
}



Re: How to implement this?

2022-04-07 Thread Elvis Zhou via Digitalmars-d-learn

On Friday, 8 April 2022 at 05:46:56 UTC, Elvis Zhou wrote:

On Friday, 8 April 2022 at 04:31:45 UTC, Elvis Zhou wrote:

[...]


I know where the issue comes from, dynamic array is GCed and 
save the reference of a local variable in GCed memory is not 
allowed, but here structs is assumed to not escape, it can be 
simply achieved by using a fixed-size array instead, ie A*[32] 
structs; int i = 0; structs[i++] = cast(A*) However I wonder 
if there be a stack allocated array with max capacity limits, 
which can be concated like with normal dynamic one.


like,

assumeNoEscapeOrWhatever!DynamicArray structs;
structs ~= cast(A*)

is it possible?


Re: How to implement this?

2022-04-07 Thread Elvis Zhou via Digitalmars-d-learn

On Friday, 8 April 2022 at 04:31:45 UTC, Elvis Zhou wrote:


struct A {}
struct B { A a; }
struct C { A a; }

A*[] structs;

B b;
init();
structs ~= cast(A*)
//Error: copying `cast(A*)& b` into allocated memory escapes a 
reference to local variable `b`


C c;
init();
structs ~= cast(A*)
//Error: copying `cast(A*)& c` into allocated memory escapes a 
reference to local variable `c`


batch_process(structs);


I know where the issue comes from, dynamic array is GCed and save 
the reference of a local variable in GCed memory is not allowed, 
but here structs is assumed to not escape, it can be simply 
achieved by using a fixed-size array instead, ie A*[32] structs; 
int i = 0; structs[i++] = cast(A*) However I wonder if there 
be a stack allocated array with max capacity limits, which can be 
concated like with normal dynamic one.


How to implement this?

2022-04-07 Thread Elvis Zhou via Digitalmars-d-learn



struct A {}
struct B { A a; }
struct C { A a; }

A*[] structs;

B b;
init();
structs ~= cast(A*)
//Error: copying `cast(A*)& b` into allocated memory escapes a 
reference to local variable `b`


C c;
init();
structs ~= cast(A*)
//Error: copying `cast(A*)& c` into allocated memory escapes a 
reference to local variable `c`


batch_process(structs);