Hard
Reference count with relaxed increments and an acquire decrement
An intrusive reference count shared by several threads. addRef() increments with memory_order_relaxed; release() decrements with memory_order_acquire and destroys the object when it observes the count going from 1 to 0. Is that ordering sufficient to make delete this safe?
main.cpp
std::atomic<int> refCount{1};
void addRef() {
refCount.fetch_add(1, std::memory_order_relaxed);
}
void release() {
if (refCount.fetch_sub(1, std::memory_order_acquire) == 1) {
delete this; // last owner: safe to destroy?
}
}15 of 51 in Concurrency