[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
pointer reference counting in C++
From: |
Kevin Peterson |
Subject: |
pointer reference counting in C++ |
Date: |
Thu, 14 Mar 2013 12:06:02 +0000 |
Got the following code for the pointer reference counting in C++, but the
answer is not as expected. Looks I am doing something wrong. Please help.
#include
using namespace std;
template class RefCountPtr {
public:
explicit RefCountPtr(T* p = NULL) {
Create(p);
}
RefCountPtr(const RefCountPtr& rhs) {
Copy(rhs);
}
RefCountPtr& operator=(const RefCountPtr& rhs) {
if(ptr_ != rhs.ptr_) {
Kill();
Copy(rhs);
}
return *this;
}
RefCountPtr& operator=(T* p) {
if(ptr_ != p) {
Kill();
Create(p);
}
return *this;
}
~RefCountPtr() {
Kill();
}
T* Get() const {
return ptr_;
}
T* operator->() const {
return ptr_;
}
T& operator* () const {
return *ptr_;
}
int GetCount() { return *count_; }
private:
T* ptr_;
int* count_;
void Create(T* p) {
ptr_ = p;
if(ptr_ != NULL) {
count_ = new int;
*count_ = 1;
} else {
count_ = NULL;
}
}
void Copy(const RefCountPtr& rhs) {
ptr_ = rhs.ptr_;
count_ = rhs.count_;
if(count_ != NULL)
++(*count_);
}
void Kill() {
if(count_ != NULL) {
if(--(*count_) == 0) {
delete ptr_;
delete count_;
}
}
}
};
void main()
{
int* pFirstInt = new int;
RefCountPtr refPointer(pFirstInt);
cout
- pointer reference counting in C++,
Kevin Peterson <=