|
From: | Kevin Peterson |
Subject: | Re: pointer reference counting in C++ |
Date: | Thu, 14 Mar 2013 17:41:38 +0530 |
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 << "count: " << refPointer.GetCount() << std::endl;
RefCountPtr refSecondPointer = refPointer; // this calls copy constructor.
cout << "second count: " << refSecondPointer.GetCount() << std::endl;
RefCountPtr refThirdPointer;
refThirdPointer = pFirstInt;
std::cout << "Third pointer: " << refThirdPointer.GetCount() << std::endl;
RefCountPtr refFourthPointer;
refFourthPointer = refSecondPointer;
cout << "Fourth count: " << refFourthPointer.GetCount() << std::endl;
return;
}
Above program is giving the following output.
count: 1
second count: 2
Third pointer: 1
Fourth count: 3
[Prev in Thread] | Current Thread | [Next in Thread] |