这是一个关于编码设计的问题,所以请原谅长代码列表:如果没有显示实际的代码,我就无法恢复这些想法和潜在的缺陷。
我正在编写一个ConcurrentReferenceCounted类,希望对我的实现提供一些反馈。该类的子类将收到“release”,而不是直接删除。
这是课程:
class ConcurrentReferenceCounted : private NonCopyable {
public:
ConcurrentReferenceCounted() : ref_count_(1) {}
virtual ~ConcurrentReferenceCounted() {}
void retain() {
ScopedLock lock(mutex_);
++ref_count_;
}
void release() {
bool should_die = false;
{
ScopedLock lock(mutex_);
should_die = --ref_count_ == 0;
}
if (should_die) delete this;
}
private:
size_t ref_count_;
Mutex mutex_;
};
这里是一个范围保留:
class ScopedRetain {
public:
ScopedRetain(ConcurrentReferenceCounted *object) : object_(object) {
retain();
}
ScopedRetain() : object_(NULL) {}
~ScopedRetain() {
release();
}
void hold(ConcurrentReferenceCounted *object) {
assert(!object_); // cannot hold more then 1 object
object_ = object;
retain();
}
private:
ConcurrentReferenceCounted *object_;
void release() {
if (object_) object_->release();
}
void retain() {
object_->retain();
}
};
最后是一个用例:
Object *target;
ScopedRetain sr;
if (objects_.get(key, &target))
sr.hold(target);
else
return;
// use target
// no need to 'release'