-
-
Save rightfold/cf926b29bc8d037c4807 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
std::mutex weakReferencesMutex; | |
std::unordered_multimap<Value*, std::atomic<Value*>> weakReferences; | |
class Value { | |
public: | |
virtual ~Value() { | |
std::lock_guard<decltype(weakReferencesMutex)> lock(weakReferencesMutex); | |
for (auto range = weakReferences.equal_range(this); range.first != range.second; ++range.first) { | |
range.first->second = nullptr; | |
} | |
weakReferences.erase(this); | |
} | |
private: | |
mutable std::atomic<long> referenceCount; | |
friend void retain(Value const&); | |
friend void release(Value const&); | |
}; | |
std::atomic<Value*> const& obtainWeakReference(Value const& value) { | |
std::lock_guard<decltype(weakReferencesMutex)> lock(weakReferencesMutex); | |
return *weakReferences.emplace(&value, std::atomic<Value*>(&value)); | |
} | |
void retain(Value const& value) { | |
++value.referenceCount; | |
} | |
void release(Value const& value) { | |
if (--value.referenceCount == 0) { | |
delete &value; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment