How to call destructor before free without dropping @nogc?

evilrat evilrat666 at gmail.com
Thu Aug 19 09:39:26 UTC 2021


On Thursday, 19 August 2021 at 08:25:23 UTC, Bienlein wrote:
>
> Oops, I just realized that you can also not call emplace when 
> @nogc is present. Well that is at least consistent with not 
> either being able to call destroy ;-).
>
> So, I guess this means that you can forget about manually 
> allocating and freeing some instance of a class and using @nogc 
> as well. That's a pitty, @nogc was a good idea.

you are probably doing something wrong, could you try @nogc ctor?

anyway @nogc is way too limiting, I don't see why bother when 
there is already `scope` storage (should work in nogc) and -vgc 
flag to show possible allocations.

```d

import core.lifetime;
import core.stdc.stdio;
import core.stdc.stdlib;

class SomeClass
{
     int a = 42;

     this() @nogc { }
     this(int val) @nogc { a = val; }
}



@nogc void main()
{
	byte[64] mem;
	mem.emplace!SomeClass();
	printf("stack %d\n", (cast(SomeClass) mem.ptr).a); // 42
	
	scope a = new SomeClass();
	printf("scope %d\n", a.a); //42
	
	SomeClass dynAlloc = cast(SomeClass) 
malloc(__traits(classInstanceSize, SomeClass));
	dynAlloc = emplace!SomeClass(dynAlloc, 123);
	printf("dynamic %d\n", dynAlloc.a); // 123
}
```


More information about the Digitalmars-d-learn mailing list