Skip to content

Add SysUtils.Exchange<T>.

Rika requested to merge runewalsh/source:exchange into main

This is a proposal out of thin air after seeing this, but I’m entirely serious.

There is already an IfThen<T> as a (bad) replacement of a ternary operator.

Add Exchange<T> next to it, that works like C++’s std::exchange.

Good use case (at least with implicit specialization... but I don’t use implicit specialization and still pretty happy with my handmade Exchange) is that this function makes type-safe FreeAndNil, FreeMemAndNil unnecessary or obsolete because you can do Exchange(obj, nil).Free, FreeMem(Exchange(ptr, nil)), and any custom counterpart: HeapFree(heap, 0, Exchange(ptr, nil)), automatically getting the useful FreeAndNil gimmick (writing nil first) for everything.

Slightly similar use (in that it swaps with nil again :D): you perform the work with several threads that might throw an exception. You catch one of the exceptions into err: TObject, and after joining threads, check it and either rethrow or free later. With Exchange, rethrowing is as simple as raise Exchange(err, nil);, without boringly introducing a variable and tossing values around (var localerr := err; err := nil; raise localerr;).

Merge request reports