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

问题描述 投票:0回答:1

我正在尝试使一个名为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}
c++ increment dynamic-memory-allocation
1个回答
0
投票
m_refcount = new (nothrow) size_t;

您的引用计数是一个指向size_t的指针,但是您尝试增加其值,而不是size_t指针的值。 size_t值本身可以通过*m_refcount访问。

© www.soinside.com 2019 - 2024. All rights reserved.