运行时总是弹出debug assertion failed
以下是代码
#include <iostream>
using namespace std;
class U_Ptr
{
friend class HasPtr;
int *ip;
size_t use;
U_Ptr(int *p): ip(p), use(1) {}
~U_Ptr() { delete ip; }
};
class HasPtr
{
public:
HasPtr(int *p, int i): ptr(new U_Ptr(p)), val(i) {}
HasPtr(const HasPtr &orig): ptr(orig.ptr), val(orig.val) {++ptr -> use;}
HasPtr& operator=(const HasPtr&);
~HasPtr() { if(--ptr -> use == 0) delete ptr;}
int get_ptr_val(){ return *ptr -> ip;}
void set_ptr_val(int i) { *ptr -> ip = i;}
private:
U_Ptr *ptr;
int val;
};
HasPtr& HasPtr::operator=(const HasPtr& rhs)
{
++rhs.ptr -> use;
if(--ptr -> use == 0)
delete ptr;
ptr = rhs.ptr;
val = rhs.val;
return *this;
}
int main()
{
int ix = 2;
HasPtr hspt(&ix, 3);
HasPtr hspt2(hspt);
cout << hspt.get_ptr_val() << endl;
hspt2.set_ptr_val(10);
cout << hspt2.get_ptr_val() << endl;
return 0;
}