我有以下代码(用 C++ 编写):
StringRef 类中的代码:
inline void retain() const {
m_refCount.fetch_add(1, std::memory_order_relaxed);
}
inline void release() const {
if(m_refCount.fetch_sub(1, std::memory_order_release) == 1){
std::atomic_thread_fence(std::memory_order_acquire);
deleteFromParent();
}
}
InternedString 中的代码:
public:
inline InternedString(){
m_ref = nullptr;
}
inline InternedString(const InternedString& other){
m_ref = other.m_ref;
if(m_ref)
m_ref->retain();
}
inline InternedString(InternedString&& other){
m_ref = other.m_ref;
other.m_ref = nullptr;
}
inline InternedString& operator=(const InternedString& other){
if(&other == this)
return *this;
if(other.m_ref)
other.m_ref->retain();
if(m_ref)
m_ref->release();
m_ref = other.m_ref;
return *this;
}
inline InternedString& operator=(InternedString&& other){
if(&other == this)
return *this;
if(m_ref)
m_ref->release();
m_ref = other.m_ref;
other.m_ref = nullptr;
return *this;
}
/*! @group Destructors */
inline ~InternedString(){
if(m_ref)
m_ref->release();
}
private:
inline InternedString(const StringRef* ref){
assert(ref);
m_ref = ref;
m_ref->retain();
}
当我在多个线程中执行此代码时,deleteFromParent() 会为同一个对象多次调用。我不明白为什么......即使我过度释放我仍然不应该得到这种行为,我想......
有人可以帮助我吗?我究竟做错了什么?