【问题标题】:How to make my m_refcount variable print out my desired values and not garbage?如何让我的 m_refcount 变量打印出我想要的值而不是垃圾?
【发布时间】:2019-11-06 07:53:56
【问题描述】:

我试图让一个名为 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 是指向 size_t 的指针?你正在增加一个指针而不是一个值
  • ++m_refcount等更改为++*m_refcount

标签: c++ increment dynamic-memory-allocation


【解决方案1】:
m_refcount = new (nothrow) size_t;

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

【讨论】:

  • 另外,使用new(nothrow) size_t 不会初始化指向的内存,即它将包含随机数据。您想改用new(nothrow) size_t()
  • 在使用 m_ptr 时会不会一样?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多