指针初始化覆盖值

Pointer initialization is overriding the value

Dog.h

class Dog
{
public:
    int *pVal;
    Dog(int);
    ~Dog();
    static int GetVal(Dog d);
};

Dog.cpp

Dog::Dog(int val)
{
    pVal = new int;
    *pVal = val;
}

Dog::~Dog()
{
    delete pVal;
}

int Dog::GetVal(Dog d)
{
    return *(d.pVal);
}

测试

Dog fido(20);
CHECK(Dog::GetVal(fido) == 20);

Dog rex(21);
CHECK(Dog::GetVal(fido) == 20);
CHECK(Dog::GetVal(rex) == 21);

第一个 CHECK 没问题。但是,一旦我声明 Dog rex(21),我的 fido 对象的 pVal 就会被 21 覆盖。通过调试,我注意到在构造函数中调用 new intrex 获得与 fido 对象的 pVal 相同的内存地址。我尝试了很多,但找不到任何东西。

初始化指针并为其赋值的正确方法是什么?

请帮忙。先感谢您。

当你拨打这个电话时:

Dog::GetVal(fido);

您在 GetVal 的参数中对 Dog 进行了 复制。调用默认的复制构造函数,它只制作 pVal 的浅拷贝。所以当副本超出范围时,pVal指向的内存被删除,这就删除了fido指向的内存。

一个解决方法是在 GetVal 中使用 Dog&,这样可以避免复制。

static int GetVal(Dog &d);

更好的选择是为您的 Dog 提供复制构造函数,如下所示:

Dog(Dog const & d) 
{ 
  pVal = new int{*(d.pVal)}; 
}

这是一个有效的 demo

关于您的观察:

I have noticed that on calling new int in the constructor the pVal of rex gets the same memory address as the fido object's pVal.

如上所述,当你调用rex的构造函数时,为fido分配的内存已经被释放,所以相同的内存可以用于rex . (当然不能保证一定会发生)。