如何让我的 m_refcount 变量打印出我想要的值而不是垃圾?

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

我正在尝试将一个名为 m_refcount 的 size_t 指针动态分配给一个新的 size_t 变量并使其从 0 递增以表明存在一个 SmartPtr 对象指向在 m_ptr 后面新分配的动态内存,但是当我打印出 m_refcount 时,我得到了垃圾。我怎样才能让它打印出它递增的值?

我没有递增,而是尝试将 m_refcount 设置为 1 和 2 之类的值,但我得到了一个错误。

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;
}

这是我的测试驱动程序的一部分,用于测试我的 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;

在测试驱动器时,我希望默认构造函数的 m_refcount 输出为 1,参数化构造函数为 0 或 1,复制构造函数为 0 或递增,析构函数为是它递减后的值m_refcount。但是只是打印出垃圾。

Testing SmartPtr Default ctor
SmartPtr Default Constructor for new allocation, RefCount=0x556825b1d2a0
Dereference Smart Pointer 1: {1,0.25}
m_refcount = new (nothrow) size_t;

您的引用计数是 pointer-to-size_t 但您尝试增加其值,而不是 size_t 指针的值。 size_t 值本身可以作为 *m_refcount.

访问