Should struct destructors be required to be @nogc?

Jonathan M Davis newsgroup.d at jmdavisprog.com
Thu Sep 14 03:03:38 UTC 2023


On Wednesday, September 13, 2023 7:39:25 PM MDT bachmeier via Digitalmars-d 
wrote:
> I recently had an invalid memory operation error, and given how
> vague that message is, I had no idea where to look for the
> problem. The problem was string concatenation in a struct
> destructor. My feeling is that destructors should always be
> @nogc, because if it's not, you've done something wrong and your
> program might unexpectedly crash.
>
> After solving the problem, I came upon [this
> page](https://wiki.dlang.org/InvalidMemoryOperationError). If the
> error message had at least included a link to that page, it would
> have saved me a lot of time.

Well, if the class or struct is on the stack, being @nogc should be
unnecessary (the same if you're using an allocator other than the GC
allocator), because it won't be run when the GC is running a collection. So,
arguably, requiring @nogc would be too restrictive for some use cases.
However, it's also true that they could just as easily be on the heap and
run into a similar issue (particularly with classes, since they almost
always live on the GC heap). So, an @nogc requirement would likely make
sense for most use cases, but I don't know how reasonable it is to
absolutely require it.

- Jonathan M Davis





More information about the Digitalmars-d mailing list