3 ms·
In plain old C it's very common to roll your own atomic reference counting. I've done it many many times. I'm surprised you haven't seen it done. GCC and MSVC b
by asveikau 2y ago
In plain old C it's very common to roll your own atomic reference counting. I've done it many many times. I'm surprised you haven't seen it done. GCC and MSVC both provide intrinsics to wrap synchronization primitives such as compare and swap (lock cmpxchg instruction on x86). __sync_bool_compare_and_swap and InterlockedCompareExchange respectively. Often you might put the reference counting in a helper function for your specific data structure.
To your second question, writing C I like to let the scope dominate the lifetime by doing a free as soon as an object goes out of scope. To make something borrow, you assign it to something with a different scope, then assign your local copy to NULL, exploiting the fact that free(NULL) is a well behaved no-op. In c++ you do the same but you can use destructors to make it more automatic.