Kevin Peterson
unread,Mar 14, 2013, 8:06:02 AM3/14/13You do not have permission to delete messages in this group
Either email addresses are anonymous for this group or you need the view member email addresses permission to view the original message
to help-gp...@gnu.org
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