Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

pointer reference counting in C++

5 views
Skip to first unread message

Kevin Peterson

unread,
Mar 14, 2013, 8:06:02 AM3/14/13
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

Kevin Peterson

unread,
Mar 14, 2013, 8:11:38 AM3/14/13
to help-gp...@gnu.org
sending again
0 new messages