65,186
社区成员




#define DISALLOW_COPY_AND_ASSIGN(TypeName) \
TypeName(const TypeName&); \
void operator=(const TypeName&)
class RefCountedBase {
protected:
~RefCountedBase() {
printf("~RefCountedBase\n");
}
RefCountedBase() : ref_count_(0) {
printf("RefCountedBase:%x\n", this);
}
void AddRef() {
++ref_count_;
}
bool Release() {
if (--ref_count_ == 0) {
return true;
}
return false;
}
private:
int ref_count_;
DISALLOW_COPY_AND_ASSIGN(RefCountedBase);
};
template <class T>
class RefCounted : public RefCountedBase {
public:
~RefCounted() {
printf("~RefCounted\n");
}
RefCounted() {
printf("RefCounted:%x\n", this);
}
void AddRef() {
RefCountedBase::AddRef();
}
void Release() {
if (RefCountedBase::Release()) {
delete static_cast<T*>(this);
}
}
private:
DISALLOW_COPY_AND_ASSIGN(RefCounted<T>);
};
template <class T>
class scoped_refptr {
public:
scoped_refptr() : ptr_(NULL) {
printf("scoped_refptr:%x\n", this);
}
scoped_refptr(T* p) : ptr_(p) {
if (ptr_)
ptr_->AddRef();
}
scoped_refptr(const scoped_refptr<T>& r) : ptr_(r.ptr_) {
if (ptr_)
ptr_->AddRef();
}
~scoped_refptr() {
if (ptr_)
ptr_->Release();
}
T* get() const { return ptr_; }
operator T*() const { return ptr_; }
T* operator->() const { return ptr_; }
scoped_refptr<T>& operator=(T* p) {
// AddRef first so that self assignment should work
if (p)
p->AddRef();
if (ptr_ )
ptr_ ->Release();
ptr_ = p;
return *this;
}
scoped_refptr<T>& operator=(const scoped_refptr<T>& r) {
return *this = r.ptr_;
}
void swap(T** pp) {
T* p = ptr_;
ptr_ = *pp;
*pp = p;
}
void swap(scoped_refptr<T>& r) {
swap(&r.ptr_);
}
private:
T* ptr_;
};
class A : public RefCounted<A>
{
public:
A(){
printf("A:%x\n", this);
}
~A(){
printf("~A\n");
}
void Afun()
{
if (this == NULL)
{
printf("NULL:%x\n", this);
return;
}
printf("afun:%x\n", this);
}
private:
DISALLOW_COPY_AND_ASSIGN(A);
};
void f()
{
scoped_refptr<A> a = new A();
a->Afun();
a = NULL;
a->Afun();
}
int _tmain(int argc, _TCHAR* argv[])
{
f();
return 0;
}