Managing malloced memory
anon
anon at anon.com
Tue Oct 12 08:35:19 UTC 2021
On Wednesday, 6 October 2021 at 18:29:34 UTC, Steven
Schveighoffer wrote:
> ```d
> struct GCWrapped(T)
> {
> private T *_val;
> this(T* val) { _val = val; }
> ref T get() { return *_val; }
> alias get this; // automatically unwrap
> ~this() { free(_val); _val = null; }
> @disable this(this); // disable copying to avoid double-free
> }
>
> GCWrapped!T *wrap(T)(T *item) {
> return new GCWrapped!T(item);
> }
>
> // usage
> auto wrapped = wrap(cFunction());
>
> // use wrapped wherever you need to access a T.
> ```
RE: @disable this(this);
I noticed that std.typecons.RefCounted only works on structs if
you set this line. How is that? Is RefCounted catching an
exception and working around it, or does the compiler treat
strcuts like GCWrapped with postblit disabled differently and use
other operations for them automatically, when it would otherwise
had copied it. My guess: OpAssign gets converted to a move
constructor automatically
More information about the Digitalmars-d-learn
mailing list