Search code examples
c++incrementdynamic-memory-allocation

How to make my m_refcount variable print out my desired values and not garbage?


I am trying to have a size_t pointer called m_refcount dynamically allocate to a new size_t variable and have it increment from 0 to show that there exists one SmartPtr object pointing the newly allocated Dynamically Memory behind m_ptr, but when I print out m_refcount I get garbage. How can I have it print out the values it increments from?

Instead of incrementing I tried setting m_refcount to values such as 1 and 2 but I get an error instead.

SmartPtr::SmartPtr()
 : m_refcount(0)
{
    m_ptr = new (nothrow) DataType;
    m_refcount = new (nothrow) size_t;
    if (m_ptr) {
        ++m_refcount;

    }
    cout << "SmartPtr Default Constructor for new allocation, RefCount=";
    cout << m_refcount << endl;
}

SmartPtr::SmartPtr(DataType *data)
 : m_ptr(data),
   m_refcount(0)
{
    m_refcount = new (nothrow) size_t;
    if (m_ptr) {
        ++m_refcount;
    }
    else {
        m_refcount = 0;
    }
    cout <<"SmartPtr Parametrized Constructor from data pointer, RefCount=";
    cout << m_refcount << endl;
}

SmartPtr::SmartPtr(const SmartPtr &other)
 : m_ptr(other.m_ptr),
   m_refcount(other.m_refcount)
{
    m_refcount = new (nothrow) size_t;
    m_refcount++;
    cout << "SmartPtr Copy Constructor, RefCount=";
    cout << m_refcount << endl;
}

SmartPtr::~SmartPtr() {
    --m_refcount;
    if (m_refcount == 0) {
        delete m_ptr;
        delete m_refcount;
    }
    else {
        cout << "SmartPtr Destructor, RefCount =";
        cout << m_refcount << endl;
    }
}

SmartPtr &SmartPtr::operator=(const SmartPtr &rhs) {
    if (this != &rhs) {
        if (--m_refcount == 0) {
            delete m_ptr;
            delete m_refcount;
        }
        m_ptr = rhs.m_ptr;
        m_refcount = rhs.m_refcount;
        ++m_refcount;
    }
    return *this;
}

DataType &SmartPtr::operator*() {
    return *m_ptr;
}

DataType *SmartPtr::operator->() {
    return m_ptr;
}

Here is a part of my test driver that tests my default constructor function for SmartPtr.

int main () {
cout << endl << "Testing SmartPtr Default ctor" << endl;
SmartPtr sp1;// Default-ctor
sp1->setIntVal(1);
sp1->setDoubleVal(0.25);
cout << "Dereference Smart Pointer 1: " << *sp1 << endl;

When testing it to a test drive I expect the output of m_refcount for my default constructor to be 1, parametrized constructor to be 0 or 1, copy constructor to be either 0 or incremented, and destructor to be the value after it decrements m_refcount. But the just prints out garbage.

Testing SmartPtr Default ctor
SmartPtr Default Constructor for new allocation, RefCount=0x556825b1d2a0
Dereference Smart Pointer 1: {1,0.25}

Solution

  • m_refcount = new (nothrow) size_t;
    

    Your refcount is a pointer-to-size_t yet you try to increment its value, not the value of a size_t pointee. The size_t value itself can be accessed as *m_refcount.